设计模式 观察者模式
首先写秘书类
import java.util.ArrayList;
import java.util.List;
public class Secretary {
private List<StockObserver> observers=new ArrayList<StockObserver>();
private String action;
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public void Attach(StockObserver observer)
{
observers.add(observer);
}
public void Notify()
{
for (StockObserver stockObserver : observers) {
stockObserver.Update();
}
}
}
在写观察者类
public class StockObserver {
private String name;
private Secretary sub;
public StockObserver(String name,Secretary sub)
{
this.name=name;
this.sub=sub;
}
public void Update()
{
System.out.println(sub.getAction()+"!!!"+name+"关闭股票行情,继续工作!");
}
}
在写测试类
public class Program {
public static void main(String[] args) {
// TODO Auto-generated method stub
Secretary secretary=new Secretary();
StockObserver worker1 = new StockObserver("施于任", secretary);
StockObserver worker2 = new StockObserver("魏国冲", secretary);
//登记着两位工友
secretary.Attach(worker1);
secretary.Attach(worker2);
//发现老板回来
secretary.setAction("老板回来了");
//通知两个同事
secretary.Notify();
}
}