官术网_书友最值得收藏!

Implementation

The following class diagram describes the structure and the actors of the chain-of-responsibility pattern:

The following classes are involved in the preceding diagram:

  • Client: This is the main structure of the application that uses the pattern. It's responsible for instantiating a chain of handlers and then for invoking the handleRequest method on the first object.
  • Handler: This is the abstract class from which all the concrete handlers have to be inherited. It has a handleRequest method, which receives the request that should be processed.
  • ConcreteHandlers: These are the concrete classes which implement a handleRequest method for each case. Each ConcreteHandler keeps a reference to the next ConcreteHandler in the chain and has to check whether it can process the request; otherwise, it has to pass it on to the next ConcreteHandler in the chain.

Each handler should implement a method that is used by the client to set the next handler to which it should pass the request if it's not able to process it. This method can be added to the base Handler class:

protected Handler successor;
public void setSuccessor(Handler successor)
{
this.successor = successor;
}

In each ConcreteHandler class, we have the following code, which checks whether it can handle the request; otherwise, it passes it on:

public void handleRequest(Request request)
{
if (canHandle(request))
{
//code to handle the request
}
else
{
successor.handleRequest();
}
}

The client is responsible for building the chain of handlers before invoking the head of the chain. The call will be propagated until it finds the right handler that can process the request.

Let's take our car service application example. We realize that each time a broken car comes in, it is first checked by the mechanic, who fixes it if the problem is in their area of expertise. If they're not able to, they send it on to the electrician. If they're not able to fix it, they pass it on to the next expert. Here's how the diagram would look:

主站蜘蛛池模板: 潞城市| 洛川县| 阿瓦提县| 连云港市| 屯昌县| 肇东市| 西吉县| 汤阴县| 通辽市| 江阴市| 明星| 阳信县| 横山县| 阳谷县| 麻栗坡县| 梁平县| 韶山市| 芜湖市| 恩施市| 如皋市| 苍梧县| 合山市| 黄平县| 广灵县| 陆河县| 宜黄县| 秦安县| 陇川县| 玉林市| 芮城县| 宁陕县| 含山县| 榆中县| 浮梁县| 盐池县| 汉寿县| 哈尔滨市| 兴海县| 岳阳市| 故城县| 驻马店市|