观察者设计模式

package com.jmj.pattern.observer;

/*

抽象观察者类
 */
public interface Observer {
    void update(String message);

}
package com.jmj.pattern.observer;

/**
 * 抽象主题角色
 */
public interface Subject {

    //添加观察者对象
    void attach(Observer observer);

    //删除订阅者
    void detach(Observer observer);

    //通知订阅者更新消息
    void notify(String message);

}
package com.jmj.pattern.observer;

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

public class SubscriptionSubject implements Subject{

    //定义一个集合,用来存储多个观察者对象
    private List weiXinUserList=new ArrayList<>();

    @Override
    public void attach(Observer observer) {
            weiXinUserList.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        weiXinUserList.remove(observer);
    }

    @Override
    public void notify(String message) {
        for (Observer observer : weiXinUserList) {
            observer.update(message);
        }
    }
}
package com.jmj.pattern.observer;

public class WeiXinUser implements Observer{

    private String name;

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

    @Override
    public void update(String message) {
        System.out.println(name+"-"+message);
    }
}
package com.jmj.pattern.observer;

public class Client {

    public static void main(String[] args) {
        //1.创建公众号对象
        SubscriptionSubject subject =new SubscriptionSubject();

        //2.订阅公众号
        subject.attach(new WeiXinUser("孙悟空"));
        subject.attach(new WeiXinUser("猪悟能"));
        subject.attach(new WeiXinUser("沙悟净"));

        //3.公众号更新,发出新消息给订阅者
        subject.notify("公众号更新了");

        ;
    }

}

观察者设计模式_第1张图片

你可能感兴趣的:(设计模式,设计模式)