Let’s make it a simple example. Suppose I have a collection of Number objects, which can then be even or odd.
Suppose I want to traverse this collection and process each element. The process depends on the type of element: even or odd.
Example: Print each element, such that:
-
if
Numberis even, I have “This is an even number.” -
if
Numberis odd, I have “This is an odd number.”
However, I may decide later that I want for only the even numbers to print “An even number.”
So, as we see, this could be solved with Inheritance and Polymorphism, through the use of virtual functions:
class Number {/*...*/}; // base class
class Even : public Number {/*...*/} // derived class
class Odd : public Number {/*...*/} // derived class
However, how can I provide the flexibility in the process to execute different behavior later on, as shown in the example above? Also, is there an alternative way to inheritance and polymorphism? Because I did not wanted to create inheritance tree only because of a specific computation/process.
The original problem is to execute different mathematical model depending on the type of an object, and the mathematical model is not unique for a given type of object (as the way I can print the even number is not unique).
Edit: It is funny that this post was closed with the argument that it is difficult to tell what is being asked. The authors of the several answers below seem to not agree with this, since all of them could understand it and reply what I was looking for.
You could separate your Strategy hierarchy from the actual numbers. This way there is no need for an artificial class hierarchy, and you are free to change associations between number (value) types and actions even runtime. The association can be defined
As an alternative approach, you can redefine your Strategies as handlers, each of which can decide whether a given value is suitable for them to handle, and process them if so. Such handlers could even be chained or stored in a collection (and then iterated over for every value), such that some values can be processed by multiple “overlapping” handlers, if this suits you.