观察者模式定义:
Define a one-to-many dependency between objects so that when one object changes state , all its dependents are notified and updated automatically .
定义对象之间的“一对多”的依赖关系,这样,当一个对象的状态发生变化时,所有依赖于这个对象的相关对象都被通知并自动更新。
观察者模式的实现:
观察者:个人投资者(Private Investors)和机构投资者(Institutions Investors)
被观察的对象:股票(Stock)
当股票价格发生一定改变时,股票去通知观察者
package pattern.part4.chapter14.pattern;
/**
* Date: 2010-8-15
* Time: 12:01:35
*/
public interface StockBuyer {
void update(float price);
}
package pattern.part4.chapter14.pattern;
/**
* Date: 2010-8-15
* Time: 12:24:54
*/
public class PrivateInvestor implements StockBuyer {
private String name;
private float maxPrice;
private float minPrice;
public PrivateInvestor(String name, float maxPrice, float minPrice, Stock stock) {
this.name = name;
this.maxPrice = maxPrice;
this.minPrice = minPrice;
stock.addBuyers(this);
}
@Override
public void update(float price) {
if (price > maxPrice) {
System.out.printf("%s is buying 500 shares...\n", name);
}
if (price < minPrice) {
System.out.printf("%s is selling 1000 stocks...\n", name);
}
}
}
package pattern.part4.chapter14.pattern;
/**
* Date: 2010-8-15
* Time: 12:27:49
*/
public class InstitutionalInvestor implements StockBuyer {
private String name;
private float maxPrice;
private float minPrice;
public InstitutionalInvestor(String name, float maxPrice, float minPrice, Stock stock) {
this.name = name;
this.maxPrice = maxPrice;
this.minPrice = minPrice;
stock.addBuyers(this);
}
@Override
public void update(float price) {
if (price > maxPrice) {
System.out.printf("%s is selling 100000 stocks...\n", name);
}
if (price < minPrice) {
System.out.printf("%s is buying 20000 shares...\n", name);
}
}
}
package pattern.part4.chapter14.pattern;
/**
* Date: 2010-8-15
* Time: 12:01:35
*/
public interface StockBuyer {
void update(float price);
}
package pattern.part4.chapter14.pattern;
/**
* Date: 2010-8-15
* Time: 12:32:27
*/
public class TestDrive {
public static void main(String[] args) {
Stock stock = new Stock(19f);
InstitutionalInvestor institutionalInvestor = new InstitutionalInvestor("Company E", 20f, 18.5f, stock);
PrivateInvestor privateInvestor = new PrivateInvestor("Xiao D", 20f, 18.9f, stock);
stock.setPrice(19.0224f);
System.out.println();
stock.setPrice(20.923f);
System.out.println();
stock.setPrice(18.8938f);
System.out.println();
stock.setPrice(19.9938f);
}
}
运行结果:
Previous price: 19.0000. Current price: 19.0224. Loss/Gain: 0.117894%.
Previous price: 19.0224. Current price: 20.9230. Loss/Gain: 9.99138%.
Company E is selling 100000 stocks...
Xiao D is buying 500 shares...
Previous price: 20.9230. Current price: 18.8938. Loss/Gain: -9.69842%.
Xiao D is selling 1000 stocks...
Previous price: 18.8938. Current price: 19.9938. Loss/Gain: 5.82201%.