• 观察者设计模式介绍


    被观察者(事件源)

    package com.dwz.concurrency2.chapter4;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Subject {
        private List<Observer> observers = new ArrayList<>();
        
        private int state;
        
        public int getState() {
            return this.state;
        }
        
        public void setState(int state) {
            if(state == this.state) {
                return;
            }
            this.state = state;
            notifyAllObserver();
        }
        
        public void attach(Observer observer) {
            observers.add(observer);
        }
        
        private void notifyAllObserver() {
            observers.stream().forEach(Observer::update);
        }
    }

    观察者抽象类

    package com.dwz.concurrency2.chapter4;
    
    public abstract class Observer {
        protected Subject subject;
        
        public Observer(Subject subject) {
            this.subject = subject;
            this.subject.attach(this);
        }
        
        public abstract void update();
    }

    观察者1-二进制观察者

    package com.dwz.concurrency2.chapter4;
    
    public class BinaryObserver extends Observer {
        
        public BinaryObserver(Subject subject) {
            super(subject);
        }
        
        @Override
        public void update() {
            System.out.println("Binary String:" + Integer.toBinaryString(subject.getState()));
        }
        
    }

    观察者2-八进制观察者

    package com.dwz.concurrency2.chapter4;
    
    public class OctalObserver extends Observer {
        
        public OctalObserver(Subject subject) {
            super(subject);
        }
        
        @Override
        public void update() {
            System.out.println("Octal String:" + Integer.toOctalString(subject.getState()));
        }
    }

    测试类

    package com.dwz.concurrency2.chapter4;
    
    public class ObserverClient {
        public static void main(String[] args) {
            final Subject subject = new Subject();
            new BinaryObserver(subject);
            new OctalObserver(subject);
            System.out.println("==================");
            subject.setState(10);
            
            System.out.println("==================");
            subject.setState(10);
            
            System.out.println("==================");
            subject.setState(15);
        }
    }    
  • 相关阅读:
    Redis 读后小感
    Redis学习笔记十:独立功能之监视器
    Redis学习笔记九:独立功能之慢查询日志
    Redis学习笔记八:独立功能之二进制位数组
    Please restart this script from an administrative PowerShell
    MSBUILD : error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”
    Macaca之Android原理浅析
    Macaca 基础原理浅析
    您需要来自XXX的权限才能对此文件夹进行更改
    JS是按值传递还是按引用传递?
  • 原文地址:https://www.cnblogs.com/zheaven/p/12107493.html
Copyright © 2020-2023  润新知