Observer模式主要通过observer的注册,当subject有什么变化时通过注册的observer,但是经典的设计中将add detach放在subject中,个人
觉得不是很好,因为注册和解绑和并不是和subject相关的行为,最好通过一个delegate将其放在一个class中来处理,因为找不到一个很好的例子
,找到某人以前的例子改写了一下。再次表示感谢。
public class HPStock extends Stock {
public HPStock(String price, InvestorHandler handler) {
super(price, handler);
// TODO Auto-generated constructor stub
}
@Override
protected void update() {
System.out.println("hp current price is"+price);
setChanged();
}
}
public class IbmStock extends Stock { public IbmStock(String price, InvestorHandler handler) { super(price, handler); } @Override protected void update() { System.out.println("ibm stock current price is"+price); setChanged(); } }
public interface IInvestor { void update(String price); }
public class InvestorHandler { private String price; public InvestorHandler(String price) { super(); this.price = price; } private List<IInvestor> listInvestor = new ArrayList<IInvestor>(); public void addInvestor(IInvestor aInvestor) { listInvestor.add(aInvestor); } public void removeInvestor(IInvestor aInvestor) { listInvestor.remove(aInvestor); } public void notifyObserver() { for (int index = 0; index < listInvestor.size(); index++) { IInvestor investor = listInvestor.get(index); investor.update(price); } } }
public class Main { /** * @param args */ public static void main(String[] args) { InvestorHandler handler = new InvestorHandler("90"); Stock mstock = new IbmStock("90", handler); mstock.addInvestor(new WallSteetInvestor()); mstock.addInvestor(new WallSteetInvestor()); mstock.addInvestor(new ShanghaiInvestor()); mstock.addInvestor(new ShanghaiInvestor()); mstock.update(); InvestorHandler handler1 = new InvestorHandler("30"); Stock hpStock = new HPStock("30", handler1); hpStock.addInvestor(new WallSteetInvestor()); hpStock.addInvestor(new WallSteetInvestor()); hpStock.addInvestor(new ShanghaiInvestor()); hpStock.addInvestor(new ShanghaiInvestor()); hpStock.update(); } }
public class ShanghaiInvestor implements IInvestor { @Override public void update(String price) { System.out.println("Shanghai investor current price is"+price); } }
public abstract class Stock { protected String price; private InvestorHandler handler; public Stock(String price, InvestorHandler handler) { super(); this.price = price; this.handler = handler; } protected abstract void update(); public void addInvestor(IInvestor aInvestor) { handler.addInvestor(aInvestor); } public void removeInvestor(IInvestor aInvestor) { handler.removeInvestor(aInvestor); } protected void setChanged() { handler.notifyObserver(); } }
public class WallSteetInvestor implements IInvestor { @Override public void update(String price) { System.out.println("wall steet current price is"+price); } }