标签:observer rri server method 传递 util import rate over
我对这个模式的理解:
被观察者在自己的内部注册观察者,当需要通知观察者的时候,就通过使用所持有的观察者自己的方法来传递消息,代码如下
Main方法
package com.test.design.observer; public class Main { public static void main(String[] args) { Activity activity = new ConcreteActivity(); Observer observer1 = new ConcreteObserver(); Observer observer2 = new ConcreteObserver(); Observer observer3 = new ConcreteObserver(); activity.addObserver(observer1); activity.addObserver(observer2); activity.addObserver(observer3); activity.notifyObserver("perimeter has been breached"); } }
被观察者接口
package com.test.design.observer; //被观察者 public interface Activity { public void addObserver(Observer observer); public void removeObserver(Observer observer); public void notifyObserver(String str); }
观察者接口
package com.test.design.observer; //抽象观察者角色 public interface Observer { public void update(String str); }
被观察者
package com.test.design.observer; import java.util.ArrayList; import java.util.List; public class ConcreteActivity implements Activity{ //存放观察者 private List<Observer> list = new ArrayList<>(); @Override public void addObserver(Observer observer) { // TODO Auto-generated method stub list.add(observer); } @Override public void removeObserver(Observer observer) { // TODO Auto-generated method stub list.remove(observer); } @Override public void notifyObserver(String str) { // TODO Auto-generated method stub for (Observer observer : list) { observer.update(str); } } }
观察者
package com.test.design.observer; /** * 具体的观察者 * @author Ash * */ public class ConcreteObserver implements Observer{ @Override public void update(String str) { // TODO Auto-generated method stub System.out.println("str"); } }
标签:observer rri server method 传递 util import rate over
原文地址:http://www.cnblogs.com/heben/p/7045031.html