觀察者模式類圖(截圖來(lái)自《大話設(shè)計(jì)模式》ps:以生活中的故事來(lái)分析設(shè)計(jì)模式,使人不覺(jué)得枯燥無(wú)味,很贊的一本書(shū)!):
成都創(chuàng)新互聯(lián)公司是少有的成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、營(yíng)銷型企業(yè)網(wǎng)站、微信小程序開(kāi)發(fā)、手機(jī)APP,開(kāi)發(fā)、制作、設(shè)計(jì)、買(mǎi)鏈接、推廣優(yōu)化一站式服務(wù)網(wǎng)絡(luò)公司,公司2013年成立,堅(jiān)持透明化,價(jià)格低,無(wú)套路經(jīng)營(yíng)理念。讓網(wǎng)頁(yè)驚喜每一位訪客多年來(lái)深受用戶好評(píng)代碼結(jié)構(gòu)圖:
Java版代碼:
import java.util.ArrayList;
public class Observer {
public static void main(String[] args) {
Subject subject= new Secretary();
AbstractObserver observer1= new StockObserver("Marry", subject);
AbstractObserver observer2= new NBAObserver("Peter", subject);
subject.attach(observer1);
subject.attach(observer2);
subject.setSbjectState("老板回來(lái)了");
subject.inform();
}
}
abstract class Subject {
private String sbjectState;
private ArrayList observers = new ArrayList<>();
public void attach(AbstractObserver observer) {
observers.add(observer);
}
public void detach(AbstractObserver observer) {
observers.remove(observer);
}
public String getSbjectState() {
return sbjectState;
}
public void setSbjectState(String sbjectState) {
this.sbjectState = sbjectState;
}
public void inform() {
for (AbstractObserver o : observers) {
o.update();
}
}
}
class Boss extends Subject {
}
class Secretary extends Subject {
}
abstract class AbstractObserver {
private String name;
private Subject sub;
public AbstractObserver(String name, Subject sub) {
this.setName(name);
this.setSub(sub);
}
public abstract void update();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Subject getSub() {
return sub;
}
public void setSub(Subject sub) {
this.sub = sub;
}
}
class StockObserver extends AbstractObserver {
public StockObserver(String name, Subject sub) {
super(name, sub);
}
public void update() {
System.out.println(this.getSub().getSbjectState() + this.getName()
+ "關(guān)閉股票行情,繼續(xù)工作!");
}
}
class NBAObserver extends AbstractObserver {
public NBAObserver(String name, Subject sub) {
super(name, sub);
}
@Override
public void update() {
System.out.println(this.getSub().getSbjectState() + this.getName()
+ "關(guān)閉NBA直播,繼續(xù)工作!");
}
}