When you need some help in a hotel, you may ask the attendant firstly, if the attend can’t help you, then the attendant may pass you question to the assistant manager, if the attendant still can’t help you, then the question maybe pass to the lobby manager.
The picture above shows the way your question passes through. In fact, you don’t need to care the path your question pass through; you just need to know, some one in the chain will give you an answer. And it has a corresponding pattern called Chain of Responsibility.
The intent of this pattern is as below.
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.
– By THE GOF BOOK
In the scene above, we may need three classes to handle the help message; further more, we need a common interface for these classes.
The class diagram will be as follows.
And if you want to use these classes, you need to specify each successor just as below.
- attendant = new Attendant () ;
- assistantManager = new AssistantManager () ;
- lobbyManager = new LobbyManager () ;
- attendant . setSuccessor ( assistantManager ) ;
- assistantManager . setSuccessor ( lobbyManager ) ;
When a client ask a question, you can simply call the attendant.helpMsg(), and in the helpMsg() method of each concrete helper, it can decide help or not depends on it’s own state. Eh, here I simply use the random number to decide pass the request or handle it. If you want to change the sequence, just change the successor by calling the setSuccessor() method.
The above introduction is a use of this pattern; someone said that it’s pure CoR (Chain of Responsibility). There is another use of this pattern, eh, it’s not pure CoR. In the not pure way, all the classes in the chain will work together to finish a job. Such as the pipeline, you can let each class take one step, then pass the request from the first one till the last one, then all the steps will finish, so the job is done. That’s all for this pattern.Download Full Project
Enjoy!