美文网首页
观察者模式

观察者模式

作者: simplerandom | 来源:发表于2020-05-20 15:14 被阅读0次
    public interface Observer {
        void accept(String message);
    }
    
    public class ConcreteObserver implements Observer {
        String name;
    
        public ConcreteObserver(String name) {
            this.name = name;
        }
    
        @Override
        public void accept(String message) {
            System.out.println("观察者:" + name + "接收消息:" + message);
        }
    }
    
    public interface BeiObserver {
        void add(Observer observer);
    
        void del(Observer observer);
    
        void send(String message);
    
    }
    
    public class ConcreteBeiObserver implements BeiObserver {
        ArrayList<Observer> list = new ArrayList<>();
    
        public ConcreteBeiObserver() {
        }
    
        public ConcreteBeiObserver(ArrayList<Observer> list) {
            this.list = list;
        }
    
        @Override
        public void add(Observer observer) {
            list.add(observer);
        }
    
        @Override
        public void del(Observer observer) {
            list.remove(observer);
        }
    
        @Override
        public void send(String message) {
            for (Observer observer : list) {
                observer.accept(message);
            }
        }
    }
    

    测试

    public class Test {
        public static void main(String[] args) {
            ConcreteObserver observer1 = new ConcreteObserver("周杰伦");
            ConcreteObserver observer2 = new ConcreteObserver("周杰");
            ConcreteBeiObserver concreteBeiObserver = new ConcreteBeiObserver();
            concreteBeiObserver.add(observer1);
            concreteBeiObserver.add(observer2);
            concreteBeiObserver.send("更新");
        }
    }
    

    相关文章

      网友评论

          本文标题:观察者模式

          本文链接:https://www.haomeiwen.com/subject/nscnohtx.html