一、观察者模式定义
类型:行为型模式
目的:当一个对象的状态发生改变时,其所有依赖者(观察者)都会收到通知并自动更新。
二、例子
2.1 菜鸟教程例子
2.1.1 定义观察者
//观察者
public abstract class Observer {
//被观察对象
protected Subject subject;
public abstract void update();
}
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) );
}
}
public class HexaObserver extends Observer{
public HexaObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println( "Hex String: " + Integer.toHexString( subject.getState() ).toUpperCase() );
}
}
2.1.2 定义被观察对象
import java.util.ArrayList;
import java.util.List;
//被观察对象
public class Subject {
//观察者列表
private List<Observer> observers = new ArrayList<Observer>();
private int state;
public int getState() {
return state;
}
public void attach(Observer observer){
observers.add(observer);
}
//通知所有观察者
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
//修改数据时,通知所有观察者
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
}
2.1.3 使用
public class ObserverPatternDemo {
public static void main(String[] args) {
//创建被观察对象
Subject subject = new Subject();
//创建观察者对象
new HexaObserver(subject);
new BinaryObserver(subject);
//创建被观察对象调用setState时,通知国有观察者
System.out.println("First state change: 15");
subject.setState(15);
System.out.println("Second state change: 10");
subject.setState(10);
}
}
2.2 JDK源码 —— Observable
2.2.1 观察者接口Observer
public interface Observer {
void update(Observable o, Object arg);
}
2.2.1 被观察者对象Observable
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;
//添加观察者
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
//通知观察者
public void notifyObservers(Object arg) {
Object[] arrLocal;
synchronized (this) {
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
}
2.3 Spring源码 —— AbstractApplicationContext
2.3.1 观察者
public class ContextStartedEvent extends ApplicationContextEvent {
public ContextStartedEvent(ApplicationContext source) {
super(source);
}
}
public class ContextStoppedEvent extends ApplicationContextEvent {
public ContextStoppedEvent(ApplicationContext source) {
super(source);
}
}
public class ContextRefreshedEvent extends ApplicationContextEvent {
public ContextRefreshedEvent(ApplicationContext source) {
super(source);
}
}
2.3.2 被观察者
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
//观察者集合
private Set<ApplicationEvent> earlyApplicationEvents;
//添加观察者Event
public void publishEvent(ApplicationEvent event) {
this.publishEvent(event, (ResolvableType)null);
}
//通知观察者Event
protected void registerListeners() {
Iterator var1 = this.getApplicationListeners().iterator();
while(var1.hasNext()) {
ApplicationListener<?> listener = (ApplicationListener)var1.next();
this.getApplicationEventMulticaster().addApplicationListener(listener);
}
String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false);
String[] var7 = listenerBeanNames;
int var3 = listenerBeanNames.length;
for(int var4 = 0; var4 < var3; ++var4) {
String listenerBeanName = var7[var4];
this.getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
Iterator var9 = earlyEventsToProcess.iterator();
while(var9.hasNext()) {
ApplicationEvent earlyEvent = (ApplicationEvent)var9.next();
this.getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
}
2.3 Guava源码 —— EventBus
public class EventBus {
//注册订阅者(观察者)
public void register(Object object) {
this.subscribers.register(object);
}
//通知订阅者(观察者)
public void post(Object event) {
Iterator<Subscriber> eventSubscribers = this.subscribers.getSubscribers(event);
if (eventSubscribers.hasNext()) {
this.dispatcher.dispatch(event, eventSubscribers);
} else if (!(event instanceof DeadEvent)) {
this.post(new DeadEvent(this, event));
}
}
}
三、其他设计模式
创建型模式
结构型模式文章来源:https://www.toymoban.com/news/detail-735521.html
- 1、设计模式——装饰器模式(Decorator Pattern)+ Spring相关源码
行为型模式文章来源地址https://www.toymoban.com/news/detail-735521.html
- 1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码
- 2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码
- 3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码
- 4、设计模式——状态模式(State Pattern)
- 5、设计模式——命令模式(Command Pattern)+ Spring相关源码
- 6、设计模式——观察者模式(Observer Pattern)+ Spring相关源码
- 7、设计模式——备忘录模式(Memento Pattern)
- 8、设计模式——模板方法模式(Template Pattern)+ Spring相关源码
- 9、设计模式——迭代器模式(Iterator Pattern)+ Spring相关源码
- 10、设计模式——责任链模式(Chain of Responsibility Pattern)+ Spring相关源码
- 11、设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码
到了这里,关于设计模式——观察者模式(Observer Pattern)+ Spring相关源码的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!