- Observer pattern: A one-to-many dependency between objects that allows multiple observer objects to simultaneously monitor a Subject object (observed).
So that when the state of an object changes, all objects that depend on it are notified and changed accordingly.
There are many ways to implement the Observer pattern: The pattern must contain two roles of the observer and the object being observed. There is a logical relationship between the observer and the observed, and when the observed changes, the observer observes the change and sends a corresponding change.
/**
* Observer Interface: Observer, the class that needs to use the observer pattern should implement this interface/
public
interface Observer
{public
void update (Object obj);
}
/**
* Observed (generally abstract, easy to expand): The method of affirming, a certain change has taken place, and the observer is informed of the change.
* * Public
interface beenobserved
{public
void Addobserver (Observer obs);//Add Watcher Object
public void Removeobserver (Observer obs);//Observer object public
void Notifyobservers (String changed);//notify observer object for corresponding change
}
/** * Target observed: Implements the interface of the observed, corresponds to the Observer object/public class Concretewatched implements
erved {//Viewer object Set private list<observer> List = new arraylist<observer> ();
@Override public void Addobserver (Observer obs)//Add the Observer {if (!list.contains (OBS)) {List.add (OBS); @Override public void Removeobserver (Observer OBS)//observer tells the observed to undo the observation, and the observed removes the observer from the container {if (list.contains) (OBS
) {List.remove (OBS); @Override public void Notifyobservers (String change) {//Traversal object, call method for Update Notification action for (Observer obs:list)
{obs.update (change); }
}
}
/**
* Target observer (specific observer)/public
class Specificwatcher implements Observer
{
@Override
public void update (Object obj)
{
System.out.println (obj.tostring ());//changes occurred
}
}
/**
* Test code
* @description: */public
class Test {public
static void Main (string[] args)
{
beenobserved bobs = new concretewatched ();
Observer OBS1 = new Specificwatcher ();
Observer OBS2 = new Specificwatcher ();
Observer OBS3 = new Specificwatcher ();
Bobs.addobserver (OBS1);//Add Observer Object
Bobs.addobserver (OBS2);
Bobs.addobserver (OBS3);
Bobs.notifyobservers ("* * * received the notice * * *);
" System.out.println ("----------Dividing Line--------------");
Bobs.removeobserver (OBS2)//Remove observer
bobs.notifyobservers ("* * * * ONE less observer * * * *)";
}
Final Print Result:
The above is the entire content of this article, I hope to learn Java program to help you.