JAVA设计模式-观察者,发布订阅

https://www.b2bchain.cn/6705.html 

package sjms;

import java.util.ArrayList;
import java.util.List;
//观察者 发布订阅模式
public class fbdy {
    //观察者接口
    public interface Watcher {
        public void update(String str);
    }
    //观察者实现
    public static class ConcreteWatcher implements Watcher {
        @Override
        public void update(String str) {
            System.out.println(str);
        }
    }


    //被观察者
    public interface Watched {
        public void addWatcher(Watcher watcher);
        public void removeWatcher(Watcher watcher);
        public void notifyWatchers(String str);
    }
    //被观察者实现
    public static class ConcreteWatched implements Watched {
        // 存放观察者列表,方便统一的管理
        private List list = new ArrayList();

        @Override
        public void addWatcher(Watcher watcher) {
            list.add(watcher);
        }

        @Override
        public void removeWatcher(Watcher watcher) {
            list.remove(watcher);
        }

        @Override
        public void notifyWatchers(String str) {
            // 遍历每一个看着自己的观察者,进行更新。
            for (Watcher watcher : list) {
                watcher.update(str);
            }
        }
    }



    public static void main(String[] args) {
        //被观察者 微信公众号
        Watched wxserver=new ConcreteWatched();
        //创建观察者 用户
        Watcher user1=new ConcreteWatcher();
        Watcher user2=new ConcreteWatcher();
        Watcher user3=new ConcreteWatcher();
        //相当于关注公众号
        wxserver.addWatcher(user1);
        wxserver.addWatcher(user2);
        wxserver.addWatcher(user3);
        //发布更新通知
        wxserver.notifyWatchers("区块链技术入门公众号更新了");
    }

}

 

你可能感兴趣的:(面试笔试,JAVA设计模式-,观察者,发布订阅)