设计模式之观察者(Observer)模式 代码详解

import java.util.ArrayList;
import java.util.List;

/**
 * User: HYY
 * Date: 13-10-28
 * Time: 下午1:34
 * To change this template use File | Settings | File Templates.
 */

/**
 * 这里使用接口是因为各个观察者可能有各自的独特的方法和属性,因此将其抽象成方法
 */
interface Observer {
    void update();
}

interface Subject {
    void addObserver(Observer observer);

    void deleteObserver(Observer observer);

    void notifyObservers();
}

class ConcreteObserver implements Observer {
    private String ObserverName;
    private Subject subject;//一个指向主题的引用,

    public ConcreteObserver(String ObserverName, Subject subject) {
        this.ObserverName = ObserverName;
        this.subject = subject;
        if (this.subject != null) {
            this.subject.addObserver(this);
        }
    }

    @Override
    public void update() {
        //在这个方法中可以通过它,来判断自己关注的数据是否发生变化,并作出相应的行动
        System.out.println(ObserverName + " 已经被更新!");
    }
}

class ConcreteSubject implements Subject {
    List<Observer> observerList;

    public ConcreteSubject() {
        this.observerList = new ArrayList<Observer>();
    }

    @Override
    public void addObserver(Observer observer) {
        if (observer != null) {
            if (observerList.contains(observer)) {
                System.out.println("已有该观察者,无需添加!");
            } else {
                observerList.add(observer);
            }
        }
    }

    @Override
    public void deleteObserver(Observer observer) {
        observerList.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observerList) {
            observer.update();
        }
    }
}

public class MyObserverTest {
    public static void main(String[] args) {
        //初始化4个观察者和一个被观察对象,构造函数自动将观察的对象附上关系
        ConcreteSubject subject = new ConcreteSubject();

        ConcreteObserver observer1 = new ConcreteObserver("观察者(1)", subject);
        ConcreteObserver observer2 = new ConcreteObserver("观察者(2)", subject);
        ConcreteObserver observer3 = new ConcreteObserver("观察者(3)", subject);
        ConcreteObserver observer4 = new ConcreteObserver("观察者(4)", subject);

        subject.notifyObservers();
    }
}

 

posted @ 2013-11-15 13:13  无忧之路  阅读(522)  评论(0编辑  收藏  举报
无忧之路