开发者

Observer pattern in non Swing applications

开发者 https://www.devze.com 2023-03-21 20:50 出处:网络
Observer pattern is very commonly used in Swing based applications. Can anybody give a prac开发者_如何学Ctical example of this pattern which can be used in non Swing, pojo applications? In the Java li

Observer pattern is very commonly used in Swing based applications. Can anybody give a prac开发者_如何学Ctical example of this pattern which can be used in non Swing, pojo applications?


In the Java libraries, almost all interfaces of the form Listener (including the AWT listeners, but there are others) point to a use of the observer pattern. There's also a basic implementation in java.util.Observable/Observer, and another in java.beans.PropertyChangeSupport


There are tons of application for the observer pattern and many don't involve GUI at all. For example consider that you are programming a stock market application. You'd like to know when the price of a stock changes.

Instead of querying the price for each stock, register your observer to a central stock broker then have him notify you every time a price changes.

The examples are countless. Whenever you want to have the state or other information about a system, instead of polling every few second, register an observer and have him notify you instead


Listener pattern is used in the JVM itself quite a lot.

For instance in Java Management Extensions (JMX) you can register asynchronous listeners (named notifications) which JVM will issue whenever some condition is met (like low memory).

I can also think of the Wicket framework, but it is actually strongly influenced by Swing in GUI building concepts.


I use the observer pattern (in conjunction with the singleton) to reflect DB changes in the application.

Every DB update occurs through a singleton-observer to which 2 other components are registered. In my case it's a vocabulary-learning application, and thus when new words are input the component responsibile for tests is notified of the change and is ready for updated tests. The other component, updates the GUI, which you don't care about. Even the test at the end is GUI-related though.

0

精彩评论

暂无评论...
验证码 换一张
取 消