美文网首页
观察者模式demo

观察者模式demo

作者: 一点点程序 | 来源:发表于2020-03-27 19:04 被阅读0次

    主题类

    package demo;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Subject {
    
        private List<Observer> observers = new ArrayList<Observer>();
        private int state;
    
        public int getState() {
            return state;
        }
    
        public void setState(int state) {
            this.state = state;
            notifyAllObservers();
        }
    
        public void attach(Observer observer){
            observers.add(observer);
        }
    
        public void notifyAllObservers(){
            for (Observer observer : observers) {
                observer.update();
            }
        }
    }
    

    观察者抽象类

    package demo;
    
    public abstract class Observer {
        protected Subject subject;
        public abstract void update();
    }
    

    观察者子类A

    package demo;
    
    public class AObserver extends Observer{
    
        public AObserver(Subject subject){
            this.subject = subject;
            subject.attach(this);
        }
    
        @Override
        public void update() {
            System.out.println( "观察者A 更新了状态: "+subject.getState());
        }
    }
    
    

    观察者子类B

    package demo;
    
    public class BObserver extends Observer{
    
        public BObserver(Subject subject){
            this.subject = subject;
            subject.attach(this);
        }
    
        @Override
        public void update() {
            System.out.println( "观察者B 更新了状态: "+subject.getState());
        }
    }
    

    测试类

    package demo;
    
    public class demo1 {
        public static void main(String[] args) {
            Subject subject = new Subject();
    
            new AObserver(subject);
            new BObserver(subject);
    
            subject.setState(8);
            System.out.println("---------分割线---------");
            subject.setState(88);
        }
    }
    
    

    运行结果

    观察者A 更新了状态: 8
    观察者B 更新了状态: 8
    ---------分割线---------
    观察者A 更新了状态: 88
    观察者B 更新了状态: 88

    相关文章

      网友评论

          本文标题:观察者模式demo

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