Design Patterns in ActionScript-Observer

In GUI programming, event-driven is an important concept. Such as, when you programming in Flex, you may put a button on the stage, then you’ll add a callback function to the button. The function will be called when there is some action play on the button, such as click. This is almost the same with the observer pattern.

 



    Make it clearer. Firstly, we care the state of the button; we want know when the button was clicked. Secondly, when the button state was changed, we want to do something, that’s the callback function. Actually, you can consider as the function cares the state of the button. When the button state change, the function will do something. The button is observable, and the function maybe the observer.

Now, let’s come to the intent of this pattern.

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

– By THE GOF BOOK

I’ll give you a new example to illustrate this pattern.

The class diagram is as follows.

clip_image001

As you see, there are only two parts in our example. One is Observable, and the other is Observer.

The role of Observable is holding the observers in a list, and notifies all the observers when the state was change. Here, we don’t have the state variable, and when you click the Notify All button in the demo the notifyAll() operation will be execute.

The Observer’s role is much simpler, just execute or update. Of course, you need to figure out which subject you’d like to focus on, and you may need to call the Observable.addObserver(yourself) to let you appear in the observer list. Then when the state is changed, execute or update method will be called automatically.

And this is pattern is also called Publish/Subscribe pattern. It means if you subscribe something, such as newspaper, you’ll get it sooner after the newspaper was published.

This pattern is very useful in dealing with GUI programming. Take it with you!

You can download the full source code from downloadhere .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值