There is a same concept for Strategy Pattern
and Inheritance
, so I can implement Strategy Pattern
with Inheritance
that sounds it is simpler and cleaner than Strategy Pattern
.
Startegy Pattern
:
class IBase
{
public:
virtual void processAction(void *data) = 0; // pure virtual
}
class Worker: public IBase
{
public:
virtual void processAction(void *data)
{
// define logic
}
}
Inheritance
:
class Base
{
public:
virtual void processAction(void *data) {}
}
class Worker: public Base
{
public:
virtual void processAction(void *data) override
{
// define logic
}
}
My question is what is the difference between them? or when should I use Strategy Pattern
or Inheritance
?
Link: Strategy Pattern
State pattern helps a class to exhibit different behaviors in a different state. Strategy Pattern encapsulates a set of related algorithms and allows the client to use interchangeable behaviors through composition and delegation at runtime.
A factory pattern is a creational pattern. A strategy pattern is an operational pattern. Put another way, a factory pattern is used to create objects of a specific type. A strategy pattern is use to perform an operation (or set of operations) in a particular manner.
Strategy Pattern is used for Behavioural decisions, while Bridge Pattern is used for Structural decisions. Brigde Pattern separats the abstract elements from the implementation details, while Strategy Pattern is concerned making algorithms more interchangeable.
The union design pattern is a structural pattern that depicts the inheritance relationship between a superclass and its subclasses. The superclass is an abstract representation of the union of all the subclasses. Due to this polymorphism, the subclasses can thus be used wherever the superclass is required.
Imagine you design a Cache. The cache can have options regarding
Now imagine you want to let the user of your cache choose any of these options, and you use inheritance. You'll need 3 * 2 * 2 = 12 different classes:
Each of the 4 LifoXxx classes will have to implement the same algorithm to implement the LIFO strategy. Same for the other ones.
Implement it with the strategy pattern instead of inheritance, and you'll have a single Cache class, and 7 strategy classes (one for each strategy), that you can combine however you want, and without code duplication.
And you can also let the user of your Cache define its own strategy, that you haven't anticipated, and let him combine it with other strategies without needing to create a whole lot of new subclasses.
Strategy is a pattern of OOP and Inheritance is a principle of OOP. Strategy is implemented using (or to support) Inheritance (actually, interface generalization).
Inheritance
Strategy
Moreover, according to your example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With