观察者模式

/**
 * 抽象被观察者接口
 */
public interface Subject {
    //注册观察者
    public void registerObserver(Observer o);
    //移除观察者
    public void removeObserver(Observer o);
    //通知
    public void notifyObserver();
}

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

/**
 * 被观察者
 */
public class ConcreteSubject implements Subject{
    private List<Observer> list;
    private String message;
    public ConcreteSubject() {
        list = new ArrayList<>();
    }
    @Override
    public void registerObserver(Observer o) {
        list.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        if (!list.isEmpty()){
            list.remove(o);
        }
    }

    @Override
    public void notifyObserver() {
        for (Observer ob : list) {
            ob.update(message);
        }
    }
    //发送消息
    public void setInformation(String s){
        this.message = s;
        System.out.println("更新消息:"+s);
        notifyObserver();//通知观察者
    }
}
/**
 * 抽象观察者
 */
public interface Observer {
    public void update(String message);
}

/**
 * 观察者
 */
public class ConcreteObserver implements Observer {
    private String name;
    private String message;

    public ConcreteObserver(String name) {
        this.name = name;
    }
    @Override
    public void update(String message) {
        this.message = message;
        read();
    }

    private void read() {
        System.out.println(name+"收到推送消息:"+message);
    }
}
import com.mod.ConcreteObserver;
import com.mod.ConcreteSubject;

/**
 * 测试
 */
public class ObserverTest {
    public static void main(String[] args){
        ConcreteSubject subject = new ConcreteSubject();
        ConcreteObserver zs = new ConcreteObserver("zs");
        ConcreteObserver ls = new ConcreteObserver("ls");
        subject.registerObserver(zs);
        subject.registerObserver(ls);
        subject.setInformation("通知:中秋放假去月球");
        subject.removeObserver(zs);
        subject.setInformation("通知:中秋节活动取消");
        //更新消息:通知:中秋放假去月球
        //zs收到推送消息:通知:中秋放假去月球
        //ls收到推送消息:通知:中秋放假去月球
        //更新消息:通知:中秋节活动取消
        //ls收到推送消息:通知:中秋节活动取消
    }
}

java封装好的

/**
 * 观察者
 */
import java.util.Observable;
import java.util.Observer;

public class Watcher implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println(o+":"+arg);
    }
}
import java.util.Observable;

/**
 * 被观察者
 */
public class BeingWatched extends Observable {
    public void setInformation(String s){
        setChanged();
        notifyObservers(s);
    }
}
//测试
import com.mod.BeingWatched;
import com.mod.Watcher;

public class ObserverDemo {
    public static void main(String[] args){
        BeingWatched watched = new BeingWatched();
        watched.addObserver(new Watcher());
        watched.setInformation("消息:。。。");
    }
    //com.mod.BeingWatched@2503dbd3:消息:。。。
}
posted @ 2019-08-28 17:01  fly_bk  阅读(131)  评论(0编辑  收藏  举报