1) Chain of Responsibility
Indent: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
责任链, 好处是降低耦合度, 因为不需要知道具体哪个对象处理了请求. 另外一个是可以运行时动态的添加一个责任(responsibility).
这个东西让我想到http server里的处理过程. 通常根据请求的url路径, 会使用不同的模块来处理, 而这些处理模块就是一个个的responsibility. 直到请求被正确dispatch为止.
代码见这里: http://sourcemaking.com/design_patterns/chain_of_responsibility/c%2523
2) Command
Indent: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
我们继续来说Java, 比如一个JButton, 要给它加一个单击事件怎么弄? 我们会调用API, addActionListener(). 首先这是一个Observer模式. 然后我们看ActionListener这个interface里的接口:
void actionPerformed(ActionEvent e);注意它的参数传递的就是一个类似于Command的东西. 当我们调用addActionListener()的时候, 实际上已经设定了命令的接收者. 所以在处理actionPerformed()的时候, 可以得到对于接收者的引用(e.getSource()).
代码: http://sourcemaking.com/design_patterns/command/c%2523
3) Interpreter
Indent: Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
这个模式我觉得很深奥. interpreter, 翻译器(虽然大多数地方翻译为"解释", 可是我觉得应该是parser啊).
Interpreter模式常用于语言的解析, 注意我说的是语言. 它跟Composite模式的区别就在这里, 看问题的角度不同. 而且Composite是结构型, 注重类的结构, 而Interpreter是行为型, 它最后的目的是要evaluate一个表达式. 书上的例子让我想到了一堆, AST(Abstract Syntax Tree), FSM(Finite State Machine), Context-Free, Regular-Expression诸如此类很恶心的东西.
大一的时候第一个project做的是一个多项式的计算器, 就是要解析表达式的, 当时自然是不知道Interpreter这个东西的, TA给了一个很难懂的算法, 其实就是把inffix转成postfix, 然后就是stack的一些操作来计算. 现在知道了Interpreter模式, 感觉能理解多了.
然后就是一个AST的问题, 大四compiler project的时候做过这个东西, 可是都忘了, 啊哈=v=
代码: http://en.wikipedia.org/wiki/Interpreter_pattern
4) Iterator
Indent: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
这个没什么好说的吧, C++的STL容器类, Java/C#的Collection系的子类, 访问其中元素使用的都是Interator模式.
代码: 书上的代码是最好的, 其它地方要么过于复杂, 要么就不能说明问题. 主要的问题是一些代码实现没有用多态来抽象Aggreate类和Iterator类的相互关系. 如果你要求不高的话, 简化版的代码可以看这里: http://sourcemaking.com/design_patterns/iterator/c++/1
5) Mediator
Indent: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
中介--b. 举一个win32 api 窗口消息的例子(好像也只能这么举, MFC/Java/C#都把事件dispatch掉了). 当窗口上的一个按钮被点了会怎么样? 会有一个窗口消息, 然后有一个DialogProc()回调函数来专门处理这个消息. 而这个函数实际上把这个窗口上所有的事件处理全部囊获了, 也就是起到了一个mediator的功能. 而当我们要换一个mediator的时候, 我们只需调用SetWindowLongPtr()把flag置成GWLP_WNDPROC, 并重新制定一个回调函数就行了.
这么说来的话, 难道mfc/java/c#的分流机制难道还不如最原始的win32 api架构? 这个我也说不好. 不过可以根据mediator的目的, 包装一些object然后协同操作. 也就是说, 一些简单的操作, 比如弹个对话框什么的dispatch机制比较好. 而比如我勾选了一个checkbox, 要enable其它一些按钮什么的, 用mediator模式. 个人理解.
代码: http://sourcemaking.com/design_patterns/mediator/c%2523



