locked
Strategy Pattern Vs Virtual Method Table RRS feed

  • Question

  • User1928065626 posted

    Hi, I came across a post on Virtual Table which states "virtual method table is a mechanism used in a programming language to support dynamic dispatch (or run-time methodbinding).

    Basically the idea is child classes of a super class either can use the default virtual method of the super class as is, or they can override the default virtual method of the super class and give their own implementation for the method as they see fit.

    The example of this concept given by the author of the post reminds me of the Strategy Pattern. It appears this method can bind data at run-time very much the same way that the Strategy Pattern does.

    Am I correct in assuming that the Virtual Method Table can be used to do the same thing that the Strategy Pattern can do?

    Please see the link below for more details on virtual method table.

    https://en.wikipedia.org/wiki/Virtual_method_table 

    Thursday, November 17, 2016 11:06 PM

Answers

  • User303363814 posted

    Sure.

    The Strategy pattern is generally implemented by having instances of subclasses.  So the overall strategy might be 'CalculateTax' and at different times you use the 'CaliforniaTax' strategy implementation or the 'NewYorkTax' strategy implementation, where CaliforniaTax and NewYorkTax would be sub-classes of CalculateTax.  (There are other ways to do it but they basically come down to the same thing).

    How does the C# compiler implement the runtime overriding of methods between these various classes?  With a virtual method table!

    Virtual method tables are a nice thing to know about from a computer science point of view but don't come into a day-to-day programmers life.  (Unless your job is writing compilers!)  A vTable, as they are commonly know, is produced by the compiler and it just works.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 18, 2016 1:50 AM