Java 设计模式 之 观察者模式
http://www.verejava.com/?id=16999149610674
package com.observer.theory;
public class Test
{
public static void main(String[] args)
{
StockData data=new StockData(16.1f,15.0f,17.2f,16.9f);
Buyer buyer=new Buyer(data);
Trading trading=new Trading(data);
data.setStockData(16.1f,15.0f,17.4f,16.9f);
data.setStockData(16.1f,14.5f,17.4f,16.9f);
}
}
package com.observer.theory;
import java.util.Observable;
import java.util.Observer;
public class Trading implements Observer
{
public Trading(Observable o)
{
o.addObserver(this);
}
@Override
public void update(Observable o, Object arg)
{
if(o instanceof StockData)
{
StockData data=(StockData)o;
System.out.println("交易报告:");
System.out.print("开盘价:"+data.getOpen());
System.out.print("收盘价:"+data.getClose());
System.out.print("最低价:"+data.getLow());
System.out.print("最高价:"+data.getHigh());
System.out.println("");
}
}
}
package com.observer.theory;
import java.util.Observable;
import java.util.Observer;
public class Buyer implements Observer
{
public Buyer(Observable o)
{
o.addObserver(this);
}
@Override
public void update(Observable o, Object arg)
{
if(o instanceof StockData)
{
StockData data=(StockData)o;
System.out.println("买家报告:");
System.out.print("开盘价:"+data.getOpen());
System.out.print("收盘价:"+data.getClose());
System.out.print("最低价:"+data.getLow());
System.out.print("最高价:"+data.getHigh());
System.out.println("");
}
}
}
package com.observer.theory;
import java.util.Observable;
import java.util.Observer;
public class StockData extends Observable
{
private float open;
private float low;
private float high;
private float close;
public StockData(float open, float low, float high, float close)
{
super();
this.open = open;
this.low = low;
this.high = high;
this.close = close;
}
public float getOpen()
{
return open;
}
public void setOpen(float open)
{
this.open = open;
}
public float getLow()
{
return low;
}
public void setLow(float low)
{
this.low = low;
}
public float getHigh()
{
return high;
}
public void setHigh(float high)
{
this.high = high;
}
public float getClose()
{
return close;
}
public void setClose(float close)
{
this.close = close;
}
public void setStockData(float open, float low, float high, float close)
{
this.open = open;
this.low = low;
this.high = high;
this.close = close;
setChanged();
notifyObservers();
}
}