Observer模式提供给关联对象一种同步通信的手段,使某个对象与依赖它的其他对象之间保持状态同步。
Observer(观察者):接口或抽象类。当Subject的状态发生变化时,Observer对象将通过一个callback函数得到通知。
待整理
/**
* @description:
* @auther: yangsj
* @created: 2019/3/21 17:25
*/
public class Blog extends Observable {
public void publishArtical(){
Artical artical = new Artical();
artical.setTitle("title");
artical.setCoutent("countent");
this.setChanged();
this.notifyObservers(artical);
}
}
/**
* @description:
* @auther: yangsj
* @created: 2019/3/21 17:28
*/
public class User implements Observer {
@Override
public void update(Observable o, Object arg) {
Artical artical = (Artical)arg;
System.out.println("title"+artical.getTitle() + " countent" + artical.getCoutent());
}
}
package com.nchu.observer;
/**
* @description:
* @auther: yangsj
* @created: 2019/3/21 17:24
*/
public class Artical {
public String title;
public String coutent;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCoutent() {
return coutent;
}
public void setCoutent(String coutent) {
this.coutent = coutent;
}
}
/**
* @description:
* @auther: yangsj
* @created: 2019/3/21 17:30
*/
public class APP {
@Test
public void Test(){
Blog blog = new Blog();
blog.addObserver(new User());
blog.publishArtical();
}
}
原文:https://www.cnblogs.com/realshijing/p/10573774.html