
本文共 2760 字,大约阅读时间需要 9 分钟。
Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects.
Behavioral patterns describe not just patterns of objects or classes but also the patterns of communication between
1. Chain of Responsibility
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.
- 当一个事件触发时,并不能知道具体谁可以处理这个事件,这个事件将沿着一个"链条"传递下去, 当有类可以处理该事件时, 便执行相应操作
- 降低了耦合程度, 应用程序只要简单的将消息传送给一个handler, 而不必关心具体谁处理,只知道必定会被合理的处理
Use Chain of Responsibility when
1. more than one object may handle a request, and the handler isn't known
2. Interpreter
Interpreter, which represents a grammar as a class hierarchy and implements an interpreter as an operator on instances of these classes.
- 当使用composite pattern时,某些operation往往是递归的。Interpreter目的就是为了处理这个operation。
- Interpreter Pattern的核心思想就是: 递归操作
- 优化方式
优化方式可以通过数据依赖分析
3. Strategy Pattern(Policy)
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.
4. Command Pattern(Action/Transaction)
Enapsulate a request as an object, thereby lettingg you parameterize clients with different request, queue or log requests, and support undoable operations
- The application configures each MenuItem with an instance of a concrete Command subclass.
- Command subclasses store the receiver of the request and invoke one or more operations on the receiver
5. Iterator Pattern(Cursor)
Provide a way to access the elements of an aggregate objects sequentially without exposing its underlying representation
The key idea in this pattern is to take the responsibility for access and traversal out of the list object and put it into an iterator object.
An iterator object is responsible for keeping track of the current element; that is, it knows which elements have been traversed already.
structure:
We make the list objects responsible for creating their corresponding iterator
6. Visitor Pattern
Represent an operation to be performed on the eleemnts of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
structure:
The visitor pattern encapsulates the operations for each compilation phase in a Visitor association with that phase.
With the Visitor pattern, you define two class hierarchies: one for the elements being openerated on(the Node hierarchy) and one for the visitors that define operations on the elements.
As long as the grammar that the compiler accepts doesn't change(we don't have to add new Node subclasses), we can add new functionality simply by defining new NodeVisitor subclass
发表评论
最新留言
关于作者
