在一个系统中,常常需要在某一对象的状态发生改变时,其他某些对象也能做出相应改变。观察者模式通常可以满足这一需求,在观察者模式中,多个观察者同时监听同一主题对象,当主题对象的状态发生改变时,会通知所有观察者对象,使他们能够自动更新自己。
Demo 创建主题类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import com.google.common.collect.Lists; import java.util.List; public class Subject { private List<Observer> observerList = Lists.newArrayList(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyAllObserver(); } public void attach(Observer observer) { observerList.add(observer); } public void notifyAllObserver() { observerList.forEach(Observer::update); } }
创建观察者抽象类 1 2 3 4 public abstract class Observer { protected Subject subject; public abstract void update(); }
创建观察者子类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class BinaryObserver extends Observer { public BinaryObserver(Subject subject) { this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println("二进制:" + 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("六进制:" + Integer.toHexString(subject.getState())); } } public class OctalObserver extends Observer { public OctalObserver(Subject subject) { this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println("八进制:" + Integer.toOctalString(subject.getState())); } }
TEST & OUTPUT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class ObserverPatternTest { public static void main(String args[]) { Subject subject = new Subject(); new BinaryObserver(subject); new HexaObserver(subject); new OctalObserver(subject); System.out.println("十进制: 10"); subject.setState(10); System.out.println("......\n十进制: 15"); subject.setState(15); } } OUTPUT: 十进制: 10 二进制:1010 六进制:a 八进制:12 ...... 十进制: 15 二进制:1111 六进制:f 八进制:17