The reason is to learn Observer mode, the main reason is or because I need to use it when using the MVC architecture design program, but I don't know how to define a complete OBServer mode, just saying that some OBServer mode has the characteristics, so Referring to the original experience, you have realized your own OBServer mode. Later, I knew what the real Observer mode is like, huh, I still introduce my own so-called OBServer mode.
Briefly introduce the characteristics of the OBSERVER mode:
1. Define a team of multi-relationships, let multiple Observer objects simultaneously listen to the object of a topic. When this topic object changes, all observer objects will be notified to enable them to automatically update.
2, the structure of the observer mode is shown below:
3, essentially, there must be an observer, and an object that can be observed. Just like playing table tennis, the players who serve were observed, while the team members were observer. When the servers played, they arouse the observer's update () method so that the team members got the ball to attack the ball.
The observer mode I implemented adopts the JavaBeans's Bound Property attribute. Everyone knows that there is a bound property in the Java Beans specification, which is when this property changes, then an event can be issued, notifying other objects of this property "cold" to arouse the associated methods of these objects. . This is consistent with the observer mode in nature.
My OBServer mode map:
code show as below:
/ * Generated by together * /
Package package1;
Import java.beans. *;
Public class observableclass {
Public string getname () {return name;}
Public void setname (String name) {
String oldValue = name;
THIS.NAME = Name;
PCS.FirePropertyChange ("Name", OldValue, Name;
}
Public Void RemovePropertyChangelistener (PropertyChangelistener PCL) {
IF (PCS == NULL) PCS = New PropertyChangeSupport (this);
PCS.RemovePropertyChangeListener (PCL);
}
Public Void AddPropertyChangeListener (PropertyChangelistener PCL) {
IF (PCS == NULL) PCS = New PropertyChangeSupport (this);
PCS.AddPropertyChangelistener (PCL);
}
PRIVATE STRING NAME;
Private PropertyChangeSupport PCS;
Private Observer LNKOBSERVER;
}
Package package1;
Import java.beans. *;
Public Class Observer Implements PropertyChangeListener {
Public Void PropertyChange (PropertyChangeEvent PCE) {
}
}
It can be seen that when the Name property of the OBSERVABLECLASS changes, a PropertyChangeEvent event will be thrown. This event automatically adds the event queue, then notifys one by one, call the PropertyChange method one by one to change the status of each observer. Practice has proven that this method can be run.
In fact, this method is a lazy way relative to authentic Observer mode, because authentic mode is the note that it is responsible for the registration to his own object, there is a NotifyAll method, and this process inside my mechanism is JavaBeans Implemented. It is really a lazy approach.