Definition-define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Advantage:
1.loosely coupled designs
when two objects are loosely coupled, they can interact, but have very little knowledge of each other. The only thing the subject knows about an observer is that it implements a certain interface. And also, we can add new observers at any time. Changes to either the subject or an observer will no affect the other.
2.Problem oriented
a.for one-to-many relationship
b.many objects wants the calls from the subject, which is always described as dependency.
publicclass PeopleSubscribe implements Observer ...{ Subject sub; private String CareerInfo; public PeopleSubscribe(Subject sub) ...{ this.sub=sub; this.sub.registerObserver(this); } publicvoid update(String Career,String Knowledge) ...{ // TODO Auto-generated method stub this.CareerInfo = Career; Display(); } privatevoid Display() ...{ System.out.println("I've subscribed the career infomation,current career info is:"); System.out.println(CareerInfo); } }
//Main.java
//codes executed
publicclass Main ...{ publicstaticvoid main(String[] args) ...{ // TODO Auto-generated method stub InfoCenter c=new InfoCenter(); Observer people1=new PeopleSubscribe(c);//subscribe the career information Observer people2=new PeopleSubscribe(c);//subscribe the career information c.SetNewInfomation("NJ Software Designer", "JDK"); c.removeObserver(people1); //remove observer c.SetNewInfomation("BJ System Analysist", "AJAX in Java"); } }