11.24观察者模式
package tutor21; import java.util.ArrayList; public class Client { public static void main(String args[]) { MySubject subject = new Stock(); MyObserver obs1; obs1=new Holders(); subject.attach(obs1); System.out.println("股票上涨"); subject.change(5); System.out.println("股票下跌"); subject.change(-5); } } class Holders implements MyObserver { public void response(int rate) { if(rate>=5) { System.out.println("股票上涨,买股票"); }else if(rate<=-5){ System.out.println("股票下跌,大哭一场"); } } } interface MyObserver { void response(int rate); } abstract class MySubject { protected ArrayList<MyObserver> observers = new ArrayList<MyObserver>(); //注册方法 public void attach(MyObserver observer) { observers.add(observer); } //注销方法 public void detach(MyObserver observer) { observers.remove(observer); } //抽象通知方法 public abstract void change(int rate); } class Stock extends MySubject { public void change(int rate) { for(Object obs : observers) { ((MyObserver)obs).response(rate); } } }