BASIC Concept Observer
- The Observer pattern (Observerpattern) is also known as the Publish subscription pattern (publish/subscribe)
- Defines a one-to -many dependency between objects, so that whenever an object changes state, all objects that depend on it are notified and updated automatically
- According to the principle of single responsibility , each class has a single function, and we can create a trigger chain by triggering mechanism to concatenate individual responsibilities into complex logical relationships in the real world.
- The role Division of the Observer Pattern (The definition of an abstract interface is provided in the JDK):
- Subject to be observed:
abstract Type , defining the duties that the observer must implement, dynamically increasing and canceling the observer
- Observer Observer:
interface , the observer receives the message and updates it to respond to the received message
- Concrete Subject/observer:
Provides the implementation of specific business logic
Problems that will be encountered in practice
- The Observer's response pattern :
- If the observer is a complex logic that causes multiple observers to listen to a single observer, it is important to determine how the observer responds by delaying the notification of the efficiency issue :
- With multithreading , starting an asynchronous thread takes a long time and does not block the main thread, that is, the asynchronous schema
- Cache Technology , caching through a large number of resources, but for stress testing, this is the synchronization architecture
- The notification needs to be customized, and the observer's logic can be reduced if the observed implementation notifies the observer, which would otherwise aggravate the observer's processing logic
Example Observer pattern
Believe that many young people can not afford to buy a house, see house price change always have feelings, this is an example of an observer pattern, we are concerned about house prices, we just as an example, to explain the application of a wide range of observer patterns
- First to implement our Observer and Subject abstract Interfaces
abstract class Subject{ new LinkedList<Observer>(); publicvoidaddObserver( Observer observer ){ list.add(observer); } publicvoidremoveObserver ( Observer observer ){ list.remove( observer); } publicabstractvoidnotifyObserver( String message );}interface Observer { void update(String message);}
Then look at the specific implementation class
Interface pricevary{String Go_high ="The price of house still go"; String Go_low =" The price of house go Low";} Class Houseprice extends Subject {@Override Public void Notifyobserver(String message) { for(Observer observer:list) {observer.update (message); }}}class Poor implements observer{@Override Public void Update(String message) {SYSTEM.OUT.PRINTLN (message +"But,what about me!"); }}class Middle Implements observer{@Override Public void Update(String message) {if(Message.equals (Pricevary.go_high)) {SYSTEM.OUT.PRINTLN (message +", I need to save more money!-_-"); }Else{SYSTEM.OUT.PRINTLN (message +"I can buy it! woh! "); }}}class Rich implements observer{@Override Public void Update(String message) {if(Message.equals (Pricevary.go_high)) {SYSTEM.OUT.PRINTLN (message +", Money coming baby! ^_^"); }Else{SYSTEM.OUT.PRINTLN (message +"fuck!"); } }} Public class observertest { Public Static void Main(String [] args) {Subject Subject =NewHouseprice (); Subject.addobserver (NewRich ()); Subject.addobserver (NewPoor ()); Subject.addobserver (NewMiddle ()); Subject.notifyobserver (Pricevary.go_high); Subject.notifyobserver (Pricevary.go_low); }}
The results of the operation are as follows, and this is the implementation of a simple observer pattern
The APIjava.util.Observer of the Observer mode provided in the JDK
- Declared as public interface Observer
- Here's how:
//一旦被监听者发生改变就会调用该方法 voidpublicupdate( Observable o , Object arg )
Java.util.Observable
- Declared as public class Observable extends Object
- Here's how:
//Add a listenervoidAddobserver (Observer o)//Get the number of listenersintCountobservers ()//Delete the specified listenervoidDeleteobserver (Observer o)//Delete all listenersvoidDeleteobservers ()//Determine if the listener has changedBooleanHasChanged ()//Notifies listeners that a listener has changed and that the action calls Clearchanged ()voidNotifyobservers ()voidNotifyobservers (Object o)//Clear 0 change of flag bitprotected void clearchanged()//Set change of flag bit, indicating changeprotected void setchanged()
So let's use the JDK API to overwrite the previous code ....
Class HousePrice1 extends Observable { Public void Priceup() {setchanged ();Super. Notifyobservers (Pricevary.go_high); } Public void Pricedown() {setchanged ();Super. Notifyobservers (Pricevary.go_low); }}class Poor1 implements java.util.observer{@Override Public void Update(Observable o, Object Arg) {String message = arg.tostring (); SYSTEM.OUT.PRINTLN (Message +"......"); }} Public class ObserverTest2 { Public Static void Main(String [] args) {HousePrice1 observable =NewHousePrice1 (); Observable.addobserver (NewPoor1 ()); Observable.priceup (); Observable.pricedown (); }}
Not written all, but enough to instruct
Use of the Observer pattern in Tomcat
- A classic use of the Observer pattern in Tomcat is to control the lifecycle of the component life cycle
- First we will use the lifecycle to correspond to the roles in The Observer pattern:
- lifecyclelistener: corresponding to abstract observer
- Serverlifecyclelisener, etc. : corresponding to the specific observer
- Lifecycle: corresponding to abstract subject
- Standardserver, etc. : corresponding to the specific subject
- In addition, there are two additional classes:
- lifecycleevent: You can define event categories, differentiate between different events, and be more flexible
- lifecyclesupport: Agent subject for observers management, will this management out of the unified implementation, later if modified as long as the Lifecyclesupport class can be modified, There is no need to modify all the subject, because all the specific subject operations on observers have been delegated to the Lifecyclesupport class.
Java design pattern (v) OBSERVER (Observer) mode and Tomcat extension