Design Patterns in ActionScript-Observer

xiaoxiao2021-03-01  9

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.

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 here .

相关资源:带音效新年烟花动画特效-HTML-代码
转载请注明原文地址: https://www.6miu.com/read-4050145.html

最新回复(0)