Strategy Pattern和Inheritance有一个相同的概念,所以我可以使用Inheritance来实现Strategy Pattern ,这种Strategy Pattern听起来比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 } }我的问题是他们之间有什么不同 ? 或者什么时候应该使用Strategy Pattern或Inheritance ?
链接: 战略模式
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
最满意答案
想象一下你设计一个Cache。 缓存可以有关于的选项
驱逐政策(LIFO,FIFO,LRU) 到期政策(读后写) 最大尺寸(元素数量,内存使用量)现在想象你想让缓存的用户选择这些选项中的任何一个,并使用继承。 你需要3 * 2 * 2 = 12个不同的类别:
LifoAfterReadNumberOfElementsBasedCache, LifoAfterReadMemoryBasedCache, 等等4个LifoXxx类中的每一个都必须实现相同的算法来实现LIFO策略。 其他人也一样。
使用策略模式而不是继承来实现它,并且您将拥有一个Cache类和7个策略类(每个策略一个),您可以根据需要进行组合,无需代码复制。
你也可以让你的Cache的用户定义自己的策略,这是你没有预料到的,并且让他将它与其他策略结合起来,而不需要创建大量新的子类。
Imagine you design a Cache. The cache can have options regarding
eviction policy (LIFO, FIFO, LRU) expiration policy (after read, after write) maximum size (number of elements, memory usage)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:
LifoAfterReadNumberOfElementsBasedCache, LifoAfterReadMemoryBasedCache, etc.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.
更多推荐
发布评论