1. Observer pattern (Observer mode)
Definition: A one-to-many relationship that belongs to a relationship between classes and classes, and does not involve inheritance.
When an object changes , other objects that depend on the object are notified and will change !
Diagram:
2. Examples of leaders informing students and teachers
2.1 Observers
Observer interface: Update method (update all subclasses) public interface Observer { //update all observervoid update ();} Student Classes Class Student implements observer{ String name; Public Student (String name) { this.name=name; } @Overridepublic void Update () {//TODO auto-generated method StubSystem.out.println (name+ "Receive notification ... ");}} Teacher Class Teacher implements observer{string name; Public Teacher (String name) { this.name=name; } @Overridepublic void Update () {//TODO auto-generated method StubSystem.out.println (name+ "Receive notification ... ");}
2.2 Main body: Leader class
//body: Manage all observers and notify observers public abstract interface Subject {//Add Observer method void Addobserver (Observer OB);//delete observer method void Removeobserver (Observer ob);//Notify All observers void Notifyobservers ();} Leadership Class Leader implements subject{//pool for all observers: Thread synchronization class Vectorprivate vector<observer> vt=new vector<observer > ();//Add observer @overridepublic void Addobserver (Observer ob) {//TODO auto-generated method Stubvt.add (OB);} Delete Observer @overridepublic void Removeobserver (Observer ob) {//TODO auto-generated method Stubvt.remove (OB);} Notifies the Observer @overridepublic Void Notifyobservers () {//calls the Update method of each observer enumeration<observer> e=vt.elements (); System.out.print ("leader informs all subordinates:"); Getcurrentdate (); while (E.hasmoreelements ()) {Observer ob=e.nextelement (); ob.update ();}} Gets the current system time public void Getcurrentdate () {Calendar cal=calendar.getinstance (); SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Date=sdf.format (Cal.gettime ()); SYSTEM.OUT.PRINTLN (date);}}
2.3 Testing
public class Test {public static void main (string[] args) {//TODO auto-generated method stub Subject leader=new L Eader (); Student stu1=new Student ("Zhang students"); Teacher t1=new Teacher ("Miss Li"); Added into the Observer pool Leader.addobserver (STU1); Leader.addobserver (t1); Notify all observers leader.notifyobservers ();}}
2.4 Running Results
The leader informs all subordinates: 2015-04-20 11:22:06 student receives the notice ... Miss Li received the notice ...
java-design Pattern (behavioral)-"Viewer mode"