一、定义
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。
二、实现
观察者模式使用三个类 Subject、Observer 和 Client。Subject 对象带有绑定观察者到 Client 对象和从 Client 对象解绑观察者的方法。我们创建 Subject 类、Observer 抽象类和扩展了抽象类 Observer 的实体类。
ObserverPatternDemo,我们的演示类使用 Subject 和实体类对象来演示观察者模式。
步骤1、创建Subject类
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class Subject { 5 6 private List<Observer> observers 7 = new ArrayList<Observer>(); 8 private int state; 9 10 public int getState() { 11 return state; 12 } 13 14 public void setState(int state) { 15 this.state = state; 16 notifyAllObservers(); 17 } 18 19 public void attach(Observer observer){ 20 observers.add(observer); 21 } 22 23 public void notifyAllObservers(){ 24 for (Observer observer : observers) { 25 observer.update(); 26 } 27 } 28 }
步骤2、创建Observer类
1 public abstract class Observer { 2 protected Subject subject; 3 public abstract void update(); 4 }
步骤3、创建实体观察者类
1 public class BinaryObserver extends Observer{ 2 3 public BinaryObserver(Subject subject){ 4 this.subject = subject; 5 this.subject.attach(this); 6 } 7 8 @Override 9 public void update() { 10 System.out.println( "Binary String: " 11 + Integer.toBinaryString( subject.getState() ) ); 12 } 13 }
1 public class OctalObserver extends Observer{ 2 3 public OctalObserver(Subject subject){ 4 this.subject = subject; 5 this.subject.attach(this); 6 } 7 8 @Override 9 public void update() { 10 System.out.println( "Octal String: " 11 + Integer.toOctalString( subject.getState() ) ); 12 } 13 }
1 public class HexaObserver extends Observer{ 2 3 public HexaObserver(Subject subject){ 4 this.subject = subject; 5 this.subject.attach(this); 6 } 7 8 @Override 9 public void update() { 10 System.out.println( "Hex String: " 11 + Integer.toHexString( subject.getState() ).toUpperCase() ); 12 } 13 }
步骤4、使用Subject和实体观察者对象
1 public class ObserverPatternDemo { 2 public static void main(String[] args) { 3 Subject subject = new Subject(); 4 5 new HexaObserver(subject); 6 new OctalObserver(subject); 7 new BinaryObserver(subject); 8 9 System.out.println("First state change: 15"); 10 subject.setState(15); 11 System.out.println("Second state change: 10"); 12 subject.setState(10); 13 } 14 }