标签:cto open tab view server vector over contract ast
观察者模式 |
我们先来解释一下观察者模式中的几个角色名称:
观察者模式的通用代码如下:
public abstract class Observer { public abstract void update(); } public class Subject { private Vector<Observer> observers = new Vector<Observer>(); public void addObserver(Observer o){ observers.add(o); } public void delObserver(Observer o){ if(observers.remove(o)) System.out.println("the observer is removed"); } public void notifyObservers(){ for(Observer o : observers){ o.update(); } } } public class ConcreteObserver extends Observer{ @Override public void update() { // TODO Auto-generated method stub System.out.println("接收消息并进行处理"); /** * 自己的业务逻辑 */ } } public class ConCreteSubject extends Subject{ public void doSomething(){ /** * 自己的业务逻辑 */ super.notifyObservers(); } }
观察者模式的优缺点 |
观察者模式的扩展 |
public class HanFeiZi extends Observable implements IHanFeiZi{ @Override public void haveBreakfast() { // TODO Auto-generated method stub super.setChanged(); super.notifyObservers("韩非子在吃饭"); } @Override public void haveFun() { // TODO Auto-generated method stub super.setChanged(); super.notifyObservers("韩非子在娱乐"); } } public class Lisi implements Observer{ @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub System.out.println("观察者接收消息处理"); } } public class Client { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Lisi lisi = new Lisi(); HanFeiZi hanfeizi = new HanFeiZi(); hanfeizi.addObserver(lisi); hanfeizi.haveBreakfast(); } }
标签:cto open tab view server vector over contract ast
原文地址:http://www.cnblogs.com/zhanglei93/p/6089882.html