UML软件工程组织

Pattern Tips 之二
作者:温昱(选自松耦合空间)



Template Method,Strategy,State。它们都是Behavioral Patterns,它们的关系如下图所示:



----------------------------------Template Method----------------------------

●Tip 1:关键字。Skeleton。

●Tip 2:图。



●Tip 3:支持变化。Subclass可以只改变算法的特定步骤,而不改变和继续使用算法的Skeleton。图中黄色的Class就是后来写的,而且工作量很小,只需Override相应的Virtual函数。其中的ConcreteClass3的改动量更小,它从已有的ConcreteClass1继承,只Override其中的一个Virtual函数。

Template Method可以说是最常见的模式,在MFC中,全局函数AfxWndProc()就是一例。

●Tip 4:支持框架。著名的Framework方面的“好莱坞法则”(Don't call us, we'll call you )就是主要由Template Method支持的“反向控制”(Superclass调用Subclass的Method)产生的。

----------------------------------Strategy----------------------------

●Tip 1:关键字。Aalgorithm Family。

●Tip 2:图。



可以看到,为了达到“将Aalgorithm从Data分离出来”的目的,代价是Context和Strategy 2 个对象。

●Tip 3:实现和使用。

实例化问题。从图中可以看到,Context和ConcreteStrategy的实例化,都将由“Application工程师”负责。

case语句。case语句到了ConcreteStrategy中了吗?“Application工程师”不写case语句了,改“Architecture工程师”要写了。有空研究一下Borland ObjectWindow的源码。

Borland ObjectWindow之Dialog验证用户输入合法性,用了Strategy模式:



●Tip 4:支持变化。Strategy lets the algorithm vary independently from clients that use it。图中的黄色Class就是假想后来扩充的。

●Tip 5:局限性。

Strategy and Context之间是紧耦合。Strategy and Context interact to implement the algorithm. A context may pass all data required by the algorithm to the strategy when the algorithm is called. Alternatively, the context can pass itself as an argument to Strategy operations. That lets the strategy call back on the context as required.

Strategy对Clients不能完全透明。Clients must be aware of different Strategies。 Therefore you should use the Strategy pattern only when the variation in behavior is relevant to clients。想想看,Client要负责ConcreteStrategy(和Context)的实例化,正是决定选哪一个ConcreteStrategy的过程,使得“Strategy对Clients不能完全透明”。

----------------------------------State----------------------------

●Tip 1:关键字。Objects for States。

没什么可说的,就是Strategy用于特殊的目的。

----------------------------------Strategy and Builder----------------------------

同Builder模式对比。同:2个东西要实例化。异:知一知2。

----------------------------------Strategy and Decorator----------------------------

Strategy: A decorator lets you change the skin of an object; a strategy lets you change the guts. These are two alternative ways of changing an object
 

上一页    下一页

 

版权所有:UML软件工程组织