观察者模式

观察者模式

当更改一个对象 可能需要更改其它对象  

 

 

 

 

public interface Observer {
    void  send (Object object);
}

-----------------------

public class Subject {
    private List<Observer> list = new ArrayList<>();
    // 加入群聊
    public void add (Observer observer){
        list.add(observer);   
    }
    // 提出群聊
    public void remove(Observer observer){
        list.remove(observer);
    }
    // 发送短信
    public void send(Object object){
        for (Observer observer:list){
            observer.send(object);
        }
    }
}

 

public class Phone1 implements Observer{
    @Override
    public void send(Object object) {
        System.out.println("接收短信" + object);
    }
}

-----------------------

public class Phone2 implements Observer{
    @Override
    public void send(Object object) {
        System.out.println("接收短信" + object);
    }
}

 

class testOne{
    public static void main(String[] args) {
        
        Subject subject = new Subject();
        Phone1 phone1 = new Phone1();
        Phone2 phone2 = new Phone2();
        // phone1 加入群聊
        subject.add(phone1);
        // phone2 加入群聊
        subject.add(phone2);
        // 发送短信
        subject.send("666666");
    }
}

2个收到短信

 

class testOne{
    public static void main(String[] args) {
        
        Subject subject = new Subject();
        Phone1 phone1 = new Phone1();
        Phone2 phone2 = new Phone2();
        // phone1 加入群聊
        subject.add(phone1);
        // phone2 加入群聊
        subject.add(phone2);
        // 发送短信
        subject.send("666666");
        System.out.println("------------------------");
        // 将phone1 踢出群聊
        subject.remove(phone1);

        // 发送短信
        subject.send("8888");
    }
}

只有一个接收短信

 

posted @ 2020-03-19 19:55  辰梓悦  阅读(126)  评论(0编辑  收藏  举报