观察者模式建立一种对象与对象之间的依赖关系,一个对象发生改变时将自动通知其他对象,其他对象将相应作出反应
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();