Let's take a look at the spirit of the Observer pattern:
The Observer pattern defines a one-to-many relationship between a series of objects. Popular metaphors are the equivalent of newspaper and subscribe people, Shui Dian ju and users. Publishers and Subscribers.
The observer pattern involves the following definitions:
Abstract theme Roles
Specific theme Roles
Abstract Observer role
Specific observer roles
1. The following is a concrete example
Take a broadcast platform notification function, its class diagram is as follows: (Tuhao is local tyrants)
Suppose the game is a big theme, and here it is equivalent to an abstract theme character:
Public interface Game { void addpeople (People people); void Removepeople (People people); void Notifypeople ();}
Abstract theme Roles have the ability to add, remove, and notify observers at their most basic
Then a specific theme , such as StarCraft in the game category, is one of the games (specific theme characters):
public class StarCraft implements Game { private arraylist<people> viewer; private String message; Public StarCraft () { viewer = new arraylist<people> (); } public void Addpeople (People people) { viewer.add (people); } public void Removepeople (People people) { if (viewer.contains (people)) { viewer.remove (people); } else { System.out.println ("No viewers!"); } } public void Setmessage (String message) { this.message = message; } public void Notifypeople () {for (people people:viewer) { people.update (message); } }}
It maintains a list of users (observers) under this topic, is responsible for removing, adding observers, sending notifications, and a series of actions.
The next step is the abstract observer role:
Public interface People { void update (String message);}
The last is the specific observer role, such as the local tyrants of the Live Fish Watch:
Public class Tuhao implements people {public void update (String message) { System.out.println ("Watch:" + message + "and send money!");} }
The final test is:
A bucket of a host on the live broadcast, and then the system will notify the person who subscribed to the live broadcast started.
Test:
@Test public void Test () { StarCraft StarCraft = new StarCraft (); Starcraft.setmessage ("Dry dead Xudong Huang!"); Local tyrants Mike tuhao Mike = new Tuhao (); Starcraft.addpeople (Mike); Starcraft.notifypeople (); } Watch: Dry dead Xudong Huang! and send money!
2. In the Java JDK, self-contained java.util.Observable and observer are abstract theme roles and abstract observer roles, respectively.
Using them to overwrite the observer's relationship is as follows:
Observable uses vector retention observers by default, and most of these methods are synchronized synchronized. However, observable is a class that inherits it and cannot inherit other classes.
Additionally, the changed flag is added, and the notification is only available when the changed flag is true, and when the notification is complete, the flag is reset to false:
The code is as follows:
public class Observable {Private Boolean changed = FALSE; Private Vector<observer> Obs; Public Observable () {obs = new vector<> (); Public synchronized void Addobserver (Observer o) {if (o = = null) throw new NullPointerException (); if (!obs.contains (o)) {obs.addelement (o); }} public synchronized void Deleteobserver (Observer o) {obs.removeelement (o); } public void Notifyobservers () {notifyobservers (null); } public void Notifyobservers (Object arg) {/* * A temporary array buffer, used as a snapshot of the STA Te of * current observers. */object[] arrlocal; Synchronized (this) {if (!changed) return; arrlocal = Obs.toarray (); Clearchanged (); } for (int i = arrlocal.length-1; i>=0; i--) ((Observer) arrlocal[i]). Update (this, ARG); } Public Synchronized void Deleteobservers () {obs.removeallelements (); } protected synchronized void Setchanged () {changed = TRUE; } protected synchronized void Clearchanged () {changed = FALSE; } public synchronized Boolean hasChanged () {return changed; } public synchronized int countobservers () {return obs.size (); }}
Specific topics:
public class StarCraft extends Observable {public void setchanged () {//observable setchanged is protected and must be implemented in the theme implementation super.setchanged (); }}
Specific observers:
public class Tuhao implements observer{public void update (Observable o, Object Arg) { System.out.println ("Local tyrants onl Ine! "); if (arg!=null) { System.out.println (arg.tostring ());}}}
Test:
@Test public void Test1 () { StarCraft StarCraft = new StarCraft (); Tuhao Mike = new Tuhao (); Starcraft.addobserver (Mike); You can see if the status changes Boolean status = Starcraft.haschanged (); System.out.println ("Whether the state changes:" +status); Starcraft.notifyobservers (); You can see the total number of objects to be notified SYSTEM.OUT.PRINTLN ("The number of people notified is:" +starcraft.countobservers ()); Change the state, here is the setchanged method of rewriting the observable starcraft.setchanged (); Status = Starcraft.haschanged (); System.out.println ("Whether the state changes:" +status); Starcraft.notifyobservers (); System.out.println ("Number of notifications:" +starcraft.countobservers ()); After the notification is complete, the status reverts to false, waiting for the next desired state Change status = Starcraft.haschanged (); System.out.println ("Whether the state changed:" +status); } status changed: false// will inform: 1// status changed: true// local tyrants online!// notification number: 1// status changed: False
In addition, you can call:
Starcraft.notifyobservers ("Additional Information");
method to pass additional information.
3. Finally, in the Java GUI, the listener is added using the Observer pattern:
JButton j = new JButton (); J.addactionlistener (New AbstractAction () {public void actionperformed (ActionEvent e) { System.out.println (" Got it! "); } );
The listener's implementation class (the anonymous inner class above) is the observer, and JButton is the subject.
As above:)
Resources:
Head First design mode
Java Watcher pattern