观察者必须在主题中注册,然后主题才能将通知观察者

观察者模式通常包括下面几个角色:

1、Subject:抽象主题,它负责管理所有观察者的引用,定时定义主要的事件操作

2、ConcreteSubject 具体主题:它实现了抽象主题定义的所有接口,当自己发生变化时会通知所有观察者

3、Observer 观察者:监听主题发生变化的接口

 

Subject

package design.pattern.observer;

public interface Subject {
    public void addObserver(Observer observer);
    public void putMsg();
}

Observer

package design.pattern.observer;

public interface Observer {
    public void run();
}

ConcreteSubject

package design.pattern.observer;

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

public class ConcreteSubject implements Subject{
    private List<Observer> list = new ArrayList<>();
    
    public void addObserver(Observer observer) {
        list.add(observer);
    }
    
    public void putMsg() {
        for (Observer observer: list) {
            observer.run();
        }
    }
}

ConcreteObserverA

package design.pattern.observer;

public class ConcreteObserverA implements Observer {
    @Override
    public void run() {
        System.out.println("ConcreteObserverA get msg");
    }

}

ConcreteObserverB

package design.pattern.observer;

public class ConcreteObserverB implements Observer{
    @Override
    public void run() {
        System.out.println("ConcreteObserverB get msg");
    }
}

Client

package design.pattern.observer;

public class Client {
    public static void main(String[] args) {
        Subject sub = new ConcreteSubject();
        sub.addObserver(new ConcreteObserverA());
        sub.addObserver(new ConcreteObserverB());
        sub.putMsg();
    }
}

 

posted on 2017-10-21 12:18  啊哈咧  阅读(126)  评论(0编辑  收藏  举报