Design Patterns in ActionScript-Chain of Responsibility

FTP-Client-128x128 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.

Question

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.

clip_image003

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 Download Full Project

Enjoy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

Leave a Reply