23种设计模式之观察者模式

观察者模式(Observer):定义了一种一对多的关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。

 

package designMode.observer;

import java.util.LinkedList;
import java.util.List;

abstract class Subject {
    
    private List<Observer> observers = new LinkedList<Observer>();
    
    public void addObserver(Observer observer){
        observers.add(observer);
    }
    public void removeObserver(Observer observer){
        observers.remove(observer);
    }
    public void notice(){
        for (Observer observer : observers) 
            observer.update();
    }
}
package designMode.observer;

class ConcreteSubject extends Subject{
    
    private String subjectState;

    public String getSubjectState() {
        return subjectState;
    }

    public void setSubjectState(String subjectState) {
        this.subjectState = subjectState;
    }
    
}
package designMode.observer;

interface Observer {
    
    public void update();
}
package designMode.observer;

class ConcreteObserver implements Observer{
    
    private String name;
    private String observerState;
    private ConcreteSubject subject;
    
    public ConcreteObserver(String name, ConcreteSubject subject) {
        this.name = name;
        this.subject = subject;
    }

    @Override
    public void update() {
        observerState = subject.getSubjectState();
        System.out.println("该观察者的新状态是:"+name+" "+observerState);
    }
    
    public String getObserverState() {
        return observerState;
    }

    public void setObserverState(String observerState) {
        this.observerState = observerState;
    }


}
package designMode.observer;

class Test {
    public static void main(String[] args) {
        ConcreteSubject s = new ConcreteSubject();
        s.addObserver(new ConcreteObserver("张三", s));
        s.addObserver(new ConcreteObserver("李四", s));
        s.addObserver(new ConcreteObserver("王五", s));
        s.setSubjectState("我更新了");
        s.notice();
    }
}

 

posted @ 2017-08-11 11:25  如果屈原会编程  阅读(142)  评论(0编辑  收藏  举报