码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之观察者模式

时间:2017-10-06 12:28:12      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:主题   之间   rgs   let   private   com   over   rem   main   

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

 

public abstract class Component {
    private List<Observer> observers = new ArrayList<>();

    public void add(Observer observer) {
        observers.add(observer);
    }

    public void delete(Observer observer) {
        observers.remove(observer);
    }

    public void notifys() {
        for (Observer observer : observers) {
            observer.update();
        }
    }
}

 

public class ConcreteComponent extends Component {
    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }
}

 

public abstract class Observer {
    public abstract void update();
}

 

public class ConcreteObserver extends Observer {
    private String name;
    private String state;
    private ConcreteComponent concreteComponent;

    public ConcreteObserver(String name, ConcreteComponent concreteComponent) {
        this.name = name;
        this.concreteComponent = concreteComponent;
    }

    @Override
    public void update() {
        state = concreteComponent.getState();
        System.out.println("观察者" + name + ",的新状态是" + state);
    }

    public ConcreteComponent getConcreteComponent() {
        return concreteComponent;
    }

    public void setConcreteComponent(ConcreteComponent concreteComponent) {
        this.concreteComponent = concreteComponent;
    }
}

 

public class ObserverDemo {
    public static void main(String[] args) {
        ConcreteComponent component = new ConcreteComponent();
        component.add(new ConcreteObserver("AA", component));
        component.add(new ConcreteObserver("BB", component));
        component.add(new ConcreteObserver("CC", component));

        component.setState("XYZ");
        component.notifys();
    }
}

 

设计模式之观察者模式

标签:主题   之间   rgs   let   private   com   over   rem   main   

原文地址:http://www.cnblogs.com/emoji1213/p/7631290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!