您的位置:首页 > 大数据 > 人工智能

design pattern notes [4] - chain of responsibility, visitor

2012-12-13 09:57 405 查看
chain of responsibility

When one object does not know which specific object will handle its request, the chain of responsibility can be used to forward request among all possible receivers to get final destination. The receivers are normally from same class hirarchy whose base
class is one action-handler composed of reference to next handler. The request can be forwarded from the most specific class to the most general class along inheritance structure.

Certainly the client may construct the chain by itself.

If an object structure contains many classes of objects with differing interaces.

Many distinct and unrelated operations need to be performed on objects in an object structure.

The classes defining the object structure rarely change, but you often want to define new operations over the structure.
The client creates one concrete visitor, and traverses the object structure, visiting each element with thevisitor. When an element is visited, it calls the Visitor operation that corresponds
to its class.
Visitor makes adding new operations easy.

Adding new concrete element class is hard. The abstrct class has to add new abstract operation.

Breaking encapsulation.

Notes more for clear understanding visitor:
Visitor let's you perform operations on elements of object structure without changing them. Two class hierarchies are defined: one for the elements of object structure being
performed operations and one for the visitors which will perform operations. We can subclass visitor to implement different operations.

The elements of object structure define Accept method and the visitors implement concrete Visit methods to visit concrete element by calling its public methods directly.

The object structure should rarely change especially for the interfaces which visitors will access otherwise the visitors have to be redefined frequently.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: