java设计模式案例详解:观察者模式
观察者模式的应用场景:
1、 对一个对象状态的更新,需要其他对象同步更新,而且其他对象的数量动态可变。
2、 对象仅需要将自己的更新通知给其他对象而不需要知道其他对象的细节。
举个例子说明,这个例子讲述一个老大吩咐小弟做事的故事,只要老大一声令下小弟就开始工作,小弟成员可增减.根据模式定义,使用两个接口,多个实现
package main.java.com.learn.observer; /** * 干活接口,接到消息的类实现该接口干活,也就是观察者 * @author garfield * */ public interface Worker { void doSomeThing(); }
package main.java.com.learn.observer; /** * 发号施令者,也就是被观察者 * Created by garfield on 2016/6/13. */ public interface Mandator { void addWorker(Worker worker); void removeWorker(Worker worker); void notifyWorker(); }
package main.java.com.learn.observer.impl; import main.java.com.learn.observer.Mandator; import main.java.com.learn.observer.Worker; import java.util.ArrayList; import java.util.List; /** * 实现发号施令,方法有添加和开除小弟,并通知小弟做事 * Created by garfield on 2016/6/13. */ public class MandatorImpl implements Mandator { private List<Worker> workers = new ArrayList<>(); @Override public void addWorker(Worker worker) { workers.add(worker); } @Override public void removeWorker(Worker worker) { workers.remove(worker); } @Override public void notifyWorker() { for (Worker worker : workers) { worker.doSomeThing(); } } }
package main.java.com.learn.observer.impl; import main.java.com.learn.observer.Worker; /** * 实现工作接口,各个小弟工作内容不一样 * Created by garfield on 2016/6/13. */ public class WorkImpl_1 implements Worker{ @Override public void doSomeThing() { System.out.println("端茶"); } }
package main.java.com.learn.observer.impl; import main.java.com.learn.observer.Worker; /** * 实现工作接口,各个小弟工作内容不一样 * Created by garfield on 2016/6/13. */ public class WorkImpl_2 implements Worker{ @Override public void doSomeThing() { System.out.println("送水"); } }
package main.java.com.learn.observer.impl; import main.java.com.learn.observer.Worker; /** * 实现工作接口,各个小弟工作内容不一样 * Created by garfield on 2016/6/13. */ public class WorkImpl_3 implements Worker{ @Override public void doSomeThing() { System.out.println("做饭"); } }
测试代码:
package main.java.com.learn.observer; import main.java.com.learn.observer.impl.MandatorImpl; import main.java.com.learn.observer.impl.WorkImpl_1; import main.java.com.learn.observer.impl.WorkImpl_2; import main.java.com.learn.observer.impl.WorkImpl_3; /** * Created by garfield on 2016/6/13. */ public class ObserverTest { public static void main(String[] args){ Mandator mandator = new MandatorImpl(); Worker worker1 = new WorkImpl_1(); Worker worker2 = new WorkImpl_2(); Worker worker3 = new WorkImpl_3(); mandator.addWorker(worker1); mandator.addWorker(worker2); mandator.addWorker(worker3); mandator.notifyWorker(); } }
这样三个小弟就开始工作了.输出结果:
端茶
送水
做饭
是不是清晰明了!