`
shake863
  • 浏览: 664735 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Design Patterns in ActionScript-Chain of Responsib

阅读更多

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.

  1. attendant = new Attendant () ;
  2. assistantManager = new   AssistantManager () ;
  3. lobbyManager = new   LobbyManager () ;
  4. attendant . setSuccessor ( assistantManager ) ;
  5. 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!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics