1. 程式人生 > >GOF設計模式之觀察者模式

GOF設計模式之觀察者模式

定義訊息釋出者介面 

package com.huhu.observer2;

public interface Observerable {

    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObserver();

}

定義觀察者介面 

package com.huhu.observer2;

public interface Observer {
    public void update(String message);
}

實現釋出者介面 

package com.huhu.observer2;

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

public class WechatServer implements Observerable {

    private List<Observer> list;
    private String message;

    public WechatServer(){
        list = new ArrayList<>();
    }

    public void registerObserver(Observer o){
        list.add(o);
    }

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

    public void notifyObserver(){
        for (Observer o: list){
            o.update(message);
        }
    }

    public void setInformation(String s){
        message = s;
        System.out.println("微信公眾號更新訊息啦");
        notifyObserver();
    }
}

實現觀察者介面

package com.huhu.observer2;

public class User implements Observer{

    private String message;
    private String name;

    public User(String name) {
        this.name = name;
    }

    public void update(String message){
        this.message = message;
        read();
    }

    public void read(){
        System.out.println(name + "收到微信訊息:" + message);
    }
}