定义
当一个对象变化时,其它依赖该对象的对象都会收到通知,并且随着变化!对象之间是一种一对多的关系。观察者模式又叫做发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。
角色
- Subject: 目标
- ConcreteSubject: 具体目标
- Observer: 观察者
- ConcreteObserver: 具体观察者
实例
创建observer
public interface Observer {
public void update(String massage);
}
创建ConcreteObserver类
public class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update(String massage) {
System.out.println(massage+" "+name);
}
}
创建subject
public interface Subject {
/**
* @author Royle.Huang
* @date 2019/1/1 17:10
* @description: 增加订阅
*/
void attach(Observer observer);
/**
* @author Royle.Huang
* @date 2019/1/1 17:11
* @description: 删除订阅
*/
void dettach(Observer observer);
/**
* @author Royle.Huang
* @date 2019/1/1 17:11
* @description: 通知订阅者
*/
void notify(String massage);
}
创建ConcreteSubject类
public class ConcreteSubject implements Subject {
List<Observer> list = new ArrayList<>();
@Override
public void attach(Observer observer) {
list.add(observer);
}
@Override
public void dettach(Observer observer) {
list.remove(observer);
}
@Override
public void notify(String massage) {
for (Observer observer : list) {
observer.update(massage);
}
}
}
测试代码
public class Test {
public static void main(String[] args) {
Observer observer = new ConcreteObserver("goudan");
Observer observer2 = new ConcreteObserver("luffy");
Observer observer3 = new ConcreteObserver("java");
Subject subject = new ConcreteSubject();
subject.attach(observer);
subject.attach(observer2);
subject.attach(observer3);
subject.notify("a message for");
}
}
运行结果
a message for goudan
a message for luffy
a message for java