标签:size rem style generate gen 操作 test 处理 span
将一个对象视作被观察者,当它发出某种行为或者发生某种变化时,通知所有依赖它的对象(观察者),这种设计模式叫做观察者设计模式。
用于处理一对多的依赖关系,当一个对象的状态发生改变时,通知所有依赖于它的对象,这些对象收到通知以后采取相应的处理措施。
package com.designmode.observer.demo01; public interface IObserver { void handleNotify(String message); }
package com.designmode.observer.demo01; import java.util.ArrayList; import java.util.List; public class Performer implements IObservable { private List<IObserver> observers; public Performer() { super(); observers = new ArrayList<IObserver>(); } @Override public void addObserver(IObserver observer) { // TODO Auto-generated method stub observers.add(observer); } @Override public void removeObserver(IObserver observer) { // TODO Auto-generated method stub observers.remove(observer); } @Override public void notifyObservers(String message) { // TODO Auto-generated method stub for (IObserver observer : observers) { observer.handleNotify(message); } } }
package com.designmode.observer.demo01; public interface IObservable { void addObserver(IObserver observer); void removeObserver(IObserver observer); void notifyObservers(String message); }
package com.designmode.observer.demo01; public class FirstObserver implements IObserver { @Override public void handleNotify(String message) { // TODO Auto-generated method stub System.out.println("观察者FirstObserver接收到消息----[" + message + "]----正在处理"); } }
package com.designmode.observer.demo01; public class SecondObserver implements IObserver { @Override public void handleNotify(String message) { // TODO Auto-generated method stub System.out.println("观察者SecondObserver接收到消息----[" + message + "]----正在处理"); } }
package com.designmode.observer.demo01; import org.junit.Test; public class ObserverTest { @Test public void test01() { /** * 创建观察者 */ IObserver firstObserver = new FirstObserver(); IObserver secondObserver = new SecondObserver(); IObservable performer = new Performer();// 创建被观察者 /** * 添加观察者 */ performer.addObserver(firstObserver); performer.addObserver(secondObserver); performer.notifyObservers("被观察者发生变化"); } }
标签:size rem style generate gen 操作 test 处理 span
原文地址:http://www.cnblogs.com/tonghun/p/6926241.html