
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.
Example coded in JAVA:
//Subject.java
import java.util.*;
public interface Subject ...{
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
//Observer.java

public interface Observer ...{
public void update(String Career,String Knowledge);
}//InfoCenter.java
//this is the concrete class of Subject

public class InfoCenter implements Subject ...{
ArrayList observers;
String CareerInfo;
String KnowledgeInfo;
public InfoCenter()
...{
observers=new ArrayList<Observer>();
}
public void notifyObservers() ...{
for(int i=0;i<observers.size();i++)
...{
Observer o=(Observer)observers.get(i);
o.update(this.CareerInfo,this.KnowledgeInfo);
}
}
public void SetNewInfomation(String CareerInfo,String KnowledgeInfo)
...{
this.CareerInfo = CareerInfo;
this.KnowledgeInfo = KnowledgeInfo;
notifyObservers();
}

public void registerObserver(Observer o) ...{
// TODO Auto-generated method stub
observers.add(o);
}
@Override
public void removeObserver(Observer o) ...{
// TODO Auto-generated method stub
int i=observers.indexOf(o);
if(i>=0)
...{
observers.remove(i);
}
}
public String GetCareerInfo()
...{
return this.CareerInfo;
}
public String GetKnowledgeInfo()
...{
return this.KnowledgeInfo;
}
}
//PeopleSubscrie.java
//this is the concrete class of observer


public class PeopleSubscribe implements Observer ...{
Subject sub;
private String CareerInfo;
public PeopleSubscribe(Subject sub)
...{
this.sub=sub;
this.sub.registerObserver(this);
}

public void update(String Career,String Knowledge) ...{
// TODO Auto-generated method stub
this.CareerInfo = Career;
Display();
}
private void Display()
...{
System.out.println("I've subscribed the career infomation,current career info is:");
System.out.println(CareerInfo);
}
}
//Main.java
//codes executed

public class Main ...{

public static void 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");
}
}
本文介绍了一种常用的设计模式——观察者模式,详细解释了其定义、优势及应用场景,并通过Java代码示例展示了如何实现该模式。
1047

被折叠的 条评论
为什么被折叠?



