1. 程式人生 > >釋出者訂閱者模式(一)

釋出者訂閱者模式(一)

自己畫了個圖


demo是用了兩個場景來描述的,一個是找工作(查的資料),一個是購物,仿照寫的,為了加深理解,根據名字可以知道訂閱者和釋出者,然後實體類分別取實現這兩個介面類,來看訂閱者

package com.fanyafeng.obser;

/**
 * Created by fanyafeng on 16/6/27.
 */
public interface Observer {
    public void update(Subject subject);
}

釋出者:
package com.fanyafeng.obser;

/**
 * Created by fanyafeng on 16/6/27.
 */
public interface Subject {
    public void registerObserver(Observer observer);

    public void removeObserver(Observer observer);

    public void notifyAllObservers();
}
這個真的可以類比一下網路購物,可以把一間店鋪類比為釋出者,然後消費者首先需要收藏可以類比訂閱才能收到店鋪的訊息,如果店鋪發訊息的話肯定所有收藏店鋪的都可以收到推送,在這也可以體會一下誰的業務比較複雜,來看具體實現

shop

package com.fanyafeng.obser.shopping;

import com.fanyafeng.obser.Observer;
import com.fanyafeng.obser.Subject;

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

/**
 * Created by fanyafeng on 16/6/28.
 */
public class Shop implements Subject {
    private ArrayList<Observer> customerList;
    private ArrayList<String> messages;

    public Shop() {
        customerList = new ArrayList<>();
        messages = new ArrayList<>();
    }

    //訂閱訊息
    @Override
    public void registerObserver(Observer observer) {
        customerList.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {

    }

    @Override
    public void notifyAllObservers() {//釋出者,通知所有訂閱者
        for (Observer observer : customerList) {
            observer.update(this);
        }
    }

    //店鋪廣播訊息
    public void postMessage(String message) {
        this.messages.add(message);
        notifyAllObservers();
    }

    public ArrayList<String> getMessages() {
        return messages;
    }

    //店鋪訊息
    public String toString() {
        return messages.toString();
    }
}
customer
package com.fanyafeng.obser.shopping;

import com.fanyafeng.obser.Observer;
import com.fanyafeng.obser.Subject;

/**
 * Created by fanyafeng on 16/6/28.
 */
public class Customer implements Observer {

    private String customer;

    public Customer(String customer) {
        this.customer= customer;
    }

    @Override
    public void update(Subject subject) {//訂閱者
        System.out.println("收到店鋪訊息的消費者:" + this.customer);
        System.out.println("店鋪訊息:" + subject.toString());
    }
}
Shop shop = new Shop();
        shop.registerObserver(new Customer("小紅"));
        shop.registerObserver(new Customer("小芳"));
        shop.registerObserver(new Customer("廣大女生"));

        shop.postMessage("鞋子降價了");
        shop.postMessage("零食降價了");
這樣就ok了