觀察者模式在對(duì)象之間存在一對(duì)多關(guān)系時(shí)使用,例如,如果一個(gè)對(duì)象被修改,它的依賴對(duì)象將被自動(dòng)通知。 觀察者模式屬于行為模式類別。
觀察者模式使用三個(gè)操作類- Subject, Observer 和 Client。Subject
是具有將觀察者附加和分離到Client
對(duì)象的方法的對(duì)象。創(chuàng)建了一個(gè)抽象類Observer
和一個(gè)具體類Subject
,它們都是擴(kuò)展了 Observer
類。
ObserverPatternDemo這是一個(gè)演示類,將使用 Subject
和具體類對(duì)象在操作中顯示觀察者模式。
觀察者模式示例的結(jié)構(gòu)如下圖所示 -
創(chuàng)建一個(gè) Subject
類,如下代碼所示 -
Subject.java
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 setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
}
創(chuàng)建一個(gè) Observer
類,如下代碼所示 -
Observer.java
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
創(chuàng)建具體的觀察者類,如下代碼所示 -
BinaryObserver.java
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() ) );
}
}
OctalObserver.java
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() ) );
}
}
HexaObserver.java
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() );
}
}
使用 Subject
和具體的觀察者對(duì)象。
ObserverPatternDemo.java
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexaObserver(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);
}
}
驗(yàn)證輸出,執(zhí)行上面的代碼得到以下結(jié)果 -
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010