觀察者模式建立一種對(duì)象與對(duì)象之間的依賴關(guān)系,一個(gè)對(duì)象發(fā)生改變時(shí)將自動(dòng)通知其他對(duì)象件已,其他對(duì)象將相應(yīng)作出反應(yīng)
public interface Observer {
public void setName(String name);
public String getName();
public void addIn();
public void reduce();
public void Infornametion(String name,int price);
}
public class Investor implements Observer {
private String name;
public Investor(String name){
this.name = name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public void addIn() {
System.out.println("add money");
}
@Override
public void reduce() {
System.out.println("reduce money");
}
@Override
public void Infornametion(String name,int price) {
System.out.println("hi "+this.name+" the share "+name+" price is "+price);
}
}
public abstract class TradingCenter {
protected String name;
protected int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public abstract void notifyObserver();
public List list = new ArrayList();
public void addInverstor(Observer ov){
list.add(ov);
}
public void removeInverstor(Observer ov){
list.remove(ov);
}
}
public class TradingCenterConcrete extends TradingCenter {
public TradingCenterConcrete(String name,int price){
this.name = name;
this.price = price;
}
public TradingCenterConcrete(){
}
@Override
public void notifyObserver() {
for(Object ob: list){
((Observer)ob).Infornametion(name,price);
}
}
}
TradingCenterConcrete tradCenter = new TradingCenterConcrete("goon",100);
Observer o1, o2,o3,o4;
o1 = new Investor("jon");
tradCenter.addInverstor(o1);
o2 = new Investor("emma");
tradCenter.addInverstor(o2);
o3 = new Investor("robert");
tradCenter.addInverstor(o3);
o4 = new Investor("hash");
tradCenter.addInverstor(o4);
tradCenter.notifyObserver();