观察者设计模式总结

1.观察者(observer)--订阅者

update 

/**
 * 观察者
 * */
public class Coder implements Observer{
    
    private String name;
    public Coder(String name){
        this.name=name;
        print("订阅者名字--"+this.name);
    }

2.被观察者(observable)--发布者

 必要条件: 设置状态发生变化,然后根据变化进行通知notify

/**
 * 
 * 被观察者
 * **/
public class TechCto extends Observable{
    
    public void publishContent(String content){
        setChanged();//设置状态发生
        this.notifyObservers(content);//调用自身的通知
    }
    

}

主函数:

public static void main(String[] args) {
        System.out.println("测试设计模式------------------------------------");
        //被观察者(发布者)
        TechCto cto =new TechCto();
        //观察者(订阅者)
        Coder coder1=new Coder("feifei");
        Coder coder2=new Coder("huahua");
        //订阅者注册到发布者上面
        cto.addObserver(coder2);
        cto.addObserver(coder1);
        //发布信息
        cto.publishContent("yumenle");
    }

测试结果:

测试设计模式------------------------------------
订阅者名字--feifei
订阅者名字--huahua
feifei   yumenle   更新成功
huahua   yumenle   更新成功
原文地址:https://www.cnblogs.com/zhengtu2015/p/7821522.html