简介
参考
https://www.runoob.com/design-pattern/observer-pattern.html
介绍
当对象间存在一对多关系时,则使用观察者模式(Observer
Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。
实现
步骤1
Subject
类对应着多个Observer
类,每当Subject
发生变化,Observer
会观察到变化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Subject { private List<Observer> observers = new ArrayList<>(); private int state;
public int getState() { return state; }
public void setState(int state) { this.state = state; notifyAllObservers(); }
public void attach(Observer observer) { observers.add(observer); }
public void notifyAllObservers() { for (Observer observer : observers) { observer.update(); } } }
|
步骤2
Observer
作为一个抽象类,可以有多个实现
1 2 3 4
| public abstract class Observer { protected Subject subject; public abstract void update(); }
|
步骤3
Observer
多个实现
BinaryObserver
1 2 3 4 5 6 7 8 9 10 11 12
| public class BinaryObserver extends Observer { public BinaryObserver(Subject subject) { this.subject = subject; this.subject.attach(this); }
@Override public void update() { System.out.println("BinaryObserver: " + Integer.toBinaryString(subject.getState())); } }
|
OctalObserver
1 2 3 4 5 6 7 8 9 10 11 12
| public class OctalObserver extends Observer {
public OctalObserver(Subject subject) { this.subject = subject; this.subject.attach(this); }
@Override public void update() { System.out.println("Octal String: " + Integer.toOctalString(subject.getState())); } }
|
HexObserver
1 2 3 4 5 6 7 8 9 10 11 12
| public class HexObserver extends Observer {
public HexObserver(Subject subject) { this.subject = subject; this.subject.attach(this); }
@Override public void update() { System.out.println("Hex String: " + Integer.toHexString(subject.getState()).toUpperCase()); } }
|
步骤4
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class ObserverPatternDemo { public static void main(String[] args) { Subject subject = new Subject();
new HexObserver(subject); new OctalObserver(subject); new BinaryObserver(subject);
System.out.println("First state change: 15"); subject.setState(15); System.out.println("Second state change: 10"); subject.setState(10); } }
|
结果
First state change: 15 Hex String: F Octal String: 17 BinaryObserver:
1111 Second state change: 10 Hex String: A Octal String: 12
BinaryObserver: 1010
扩展
从观察者模式很容易能联想到微服务架构下的注册中心,注册中心的职责不就是监听者注册了的服务,向服务消费者提供需要的服务。这就和观察者模式很相像了,每当我们的服务变化,注册中心也会观察到变化,进而改变该服务在注册中心的状态信息,保证能提供稳定可靠的服务。
未来会学习并思考,注册中心到底是如何实现的。