举例: 观察者模式实现注册的投资者在股票市场发生变化是,可以自动得到通知的功能(UML类图+代码) (观察者模式实现老板,前台和员工,两者是通知者,员工是观察者)
UML类图
代码:
抽象观察者Observer:
package 观察者模式;
public abstract class Observer {
public abstract void Update();
}
具体观察者ConcreteObserver:
package 观察者模式;
public class ConcreteObserver extends Observer {
private String name;
private String observerState;
private ConcreteSubject subject;
public ConcreteObserver(ConcreteSubject subject,String name){
this.subject=subject;
this.name=name;
}
@Override
public void Update() {
observerState=subject.getSubjectState();
System.out.println("观察者"+name+"的新状态"+observerState);
}
public ConcreteSubject getSubject() {
return subject;
}
public void setSubject(ConcreteSubject subject) {
this.subject = subject;
}
}
抽象通知者Subject:
package 观察者模式;
import java.util.ArrayList;
public abstract class Subject {
private ArrayList<Observer> observers=new ArrayList<Observer>();
public void Attach(Observer observer){
observers.add(observer);
}
public void Detach(Observer observer){
observers.remove(observer);
}
public void Notify(){
for(int i=0;i<observers.size();i++){
observers.get(i).Update();
}
}
}
具体通知者ConcreteSubject:
package 观察者模式;
public class ConcreteSubject extends Subject {
private String subjectState;
public String getSubjectState() {
return subjectState;
}
public void setSubjectState(String subjectState) {
this.subjectState = subjectState;
}
}
客户端Client:
package 观察者模式;
public class Client {
public static void main(String[] args) {
ConcreteSubject s=new ConcreteSubject();
s.Attach(new ConcreteObserver(s, "投资者1"));
s.Attach(new ConcreteObserver(s, "投资者2"));
s.Attach(new ConcreteObserver(s, "投资者3"));
s.setSubjectState("ABC");
s.Notify();
}
}
运行结果:
观察者投资者1的新状态ABC
观察者投资者2的新状态ABC
观察者投资者3的新状态ABC
|