首先看Strategy和Decorator在GoF的《Design Patterns》的intent
Decorator
(1)intent:
Attach additional responsibilities to an object dynamically.Decorators provide a flexible alternative to subclassing for extending functionality.
(2)UML Diagram:
Strategy
(1)intent
Define a family of algorithms,encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary indepedently from clients that use it.
(2)UML diagram:
(CHYGO)问:如果把Decarator中的Additional responsibilities看成是a family of algorithms,那么Strategy和Decorator不都是一样的么?两种Patterns有什么异同?
(CHYGO)答:
(1)按蜡笔先生提供的思路,首先从两种模式的所属的Purpose下手:
Decorator属于Structural Patterns;Stratery属于Behavioral Patterns.那么两种Purpose(或者说3种Purpose的区别是什么?)
a.来自《设计模式解析》
创建型 意图:创建或实例化对象 用途:实例化对象
结构性 意图:将已有的对象组合起来 用途:处理结构,将实现与抽象联系起来
行为型 意图:给出一种提供灵活(变化)行为的方式 用途:封装变化
b.来自GoF的《Design Patterns》
Creational:the process of object creation
Structural:the composition od classes or objects
Behavioral:characterize the way in which classes or objects interact and distribute responsibility
可注意到Structural的特征是“对象的组合”;而Behavioral的特性是:提供灵活的行为方式。关键的区别点在于是否涉及到对象的组合。于是再往下分析,Strategy是把Class Stratefy聚集到Class Content中,由Content调用Strategy的AlgorithmInterface(),所以可以推知Strategy属于对象的组合。wow,Hold on~GoF是把Strategy归为Behavioral一类的,很明显不可能是他们错了。我觉得应该这么分析,Strategy这个类封装了算法的变化,然后content中不能显式的看到这种变化,所以Stategy为Behavioral Pattern?这样分析是否正确?如果学习到接下来的Behavioral Pattern我会验证的。
那Decorator呢,关注主要的类Decorator(我的理解是看purpose主要看主要功能类的地位,在Decorator中主要功能类就是Decorator)。由UML Diagram可见,Component是Class Decorator的父类,Class Decorator在派生各种不同的Decorator功能。这好像就是“类爆炸”啊?
注意,Class Decorator的父类Component又聚集到了Class Decorator中。也就是说用同样派生自component的Class ConcreteComponent和Class Decorator(Decorator的子类)进行组合,所以是Structural Pattern?(这样的分析是否正确待以后验证)
在看两种模式的main()代码:
Strategy
int main(int argc,char* argv[])
{ Strategy* ps = new ConcreteStrategyA();Context* pc = new Context(ps);pc->DoAction();if (NULL != pc) delete pc;return 0;
}
Decorator
int main(int argc,char* argv[])
{ Component* com = new ConcreteComponent();Decorator* dec = new ConcreteDecorator(com);dec->Operation();delete dec;return 0;
}
咋一看上去好像两者的main()代码都是一样的(Decorator指向的是子类对象,而Context指向的是自身的对象,这是唯一的不同)。两段代码关键就在于Strategy和Context是纯粹的聚合关系。而Component和Decorator是派生+聚合关系;
本人愚钝,对Design Patterns还没有很好的理解。嗯嗯,继续努力。