zoukankan      html  css  js  c++  java
  • Android Observer观察模式基础入门

    import java.util.ArrayList;
    import java.util.List;
    
    public abstract class Subject {
        /**
         * 保存女朋友的集合
         */
        private List<Observer> list = new ArrayList();
    
        /**
         * 添加人
         * 
         * @param server
         */
        public void attach(Observer server) {
            list.add(server);
            System.out.println("我新交了一个女朋友,名字叫做:" + server.getName());
        }
    
        /**
         * 移除人
         * 
         * @param server
         */
        public void detach(Observer server) {
            list.remove(server);
            System.out.println("我和她分手了");
        }
    
        /**
         * 通知所有的女朋友更新状态
         */
        public void notifyObserver(String state) {
            for (Observer observer : list) {
                observer.update(state);
            }
        }
    }
    public interface Observer {
    
        public String getName();
    
        void update(String state);
    }
    public class MessageSubject extends Subject {
    
        public void onClick(String state) {
            notifyObserver(state);
        }
    }
    public class GFObserver implements Observer {
    
        public GFObserver(String name) {
            this.name = name;
        }
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void update(String state) {
            System.out.println(this.name + "接收到新消息,男朋友最新状态:" + state);
        }
    }
    public class Client {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Observer obser1 = new GFObserver("范冰冰");
            Observer obser2 = new GFObserver("杨幂");
            Observer obser3 = new GFObserver("Sisi");
            Observer obser4 = new GFObserver("sasa");
            MessageSubject message = new MessageSubject();
            message.attach(obser1);
            message.attach(obser2);
            message.attach(obser3);
            message.attach(obser4);
            message.onClick("我在大保健");
            
            message.detach(obser1);
            message.onClick("泡吧");
        }
    }

  • 相关阅读:
    Epic OA Day2 2014/11/7
    LeetCode day15 2014/11/3
    LeetCode day14 2014/11/2
    Bluetooth BQB PTS(Profile Tuning Suite)
    音频编码:ADPCM
    软件推荐 : USB Over Network
    IOS的BLE蓝牙连接参数限制
    python pyinstaller
    QCC3003x BLE 设置私有地址
    QCC300x UART
  • 原文地址:https://www.cnblogs.com/xiaoyao095/p/7007614.html
Copyright © 2011-2022 走看看