观察者模式 股票实例

演示注册的投资者在股票市场发生变化时,可以自动得到通知

观察者模式 股票实例_第1张图片
抽象通知者:

public abstract class Stock {

	protected String symbol;
	protected double price;
	private ArrayList<Investor> investors=new ArrayList<Investor>();
	
	public Stock(String symbol, double price) {
		super();
		this.symbol = symbol;
		this.price = price;
	}

	public String getSymbol() {
		return symbol;
	}

	public void setSymbol(String symbol) {
		this.symbol = symbol;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
		Notify();
	}
	
	public void Attach(Investor investor) {
		investors.add(investor);
	}
	
	public void Detach(Investor investor) {
		investors.remove(investor);
	}
	public void Notify() {
		for(Investor i:investors)
			i.Update(this);
	}
}

具体通知者:

public class IBM extends Stock {

	/**
	 * @param symbol
	 * @param price
	 */
	public IBM(String symbol, double price) {
		super(symbol, price);
		
	}
}

观察者接口:

public interface IInvestor {

	void Update(Stock stock);
}

具体观察者:

public class Investor implements IInvestor {

	private String name;
	private Stock stock;
	
	public Investor(String name) {
		this.name = name;
	}

	public Stock getStock() {
		return stock;
	}

	public void setStock(Stock stock) {
		this.stock = stock;
	}

	@Override
	public void Update(Stock stock) {
		System.out.println(name+" "+stock.symbol+" "+stock.price);
	}

}

客户端:

public class Main {

	public static void main(String[] args) {
		
		Investor s=new Investor("aaa");
		Investor b=new Investor("bbb");
		
		IBM ibm=new IBM("IBM",120);
		ibm.Attach(s);
		ibm.Attach(b);
		
		ibm.setPrice(120.00);
		ibm.setPrice(120.70);
		ibm.setPrice(120.32);
		ibm.setPrice(120.48);
	}

}

你可能感兴趣的:(设计模式)