觀察者模式:
當(dāng)對(duì)象間存在一對(duì)多關(guān)系時(shí)曙旭,則使用觀察者模式(Observer Pattern)盗舰。比如,當(dāng)一個(gè)對(duì)象被修改時(shí)桂躏,則會(huì)自動(dòng)通知它的依賴對(duì)象钻趋。觀察者模式屬于行為型模式。
Java 實(shí)現(xiàn)觀察者(Observer)模式 參考
- https://blog.csdn.net/jjwwmlp456/article/details/39967021
- https://www.runoob.com/design-pattern/observer-pattern.html
初始化:
public void init() {
checkWorkList();
ListenerRunnable listenerRunnable = new ListenerRunnable();
ListenerThreadObserver observer = new ListenerThreadObserver(); //初始化監(jiān)聽線程的觀察者實(shí)例
listenerRunnable.addObserver(observer); // 作為參數(shù)傳給監(jiān)聽線程
Thread listenerThread = new Thread(listenerRunnable);
listenerThread.setDaemon(true);
listenerThread.start();
}
觀察者:
class ListenerThreadObserver implements Observer {
@Override
public void update(Observable o, Object arg) {
try {
Thread.sleep(properties.getSleepTime());
} catch (InterruptedException e) {
logger.warn(e.getMessage());
}
init(); // 接收到數(shù)據(jù)變化的通知剂习,則重新初始化蛮位,創(chuàng)建線程
logger.info("The encoder listener server has bean restarted!");
}
}
監(jiān)聽線程:
class ListenerRunnable extends Observable implements Runnable {
@Override
public void run() {
try {
while (true) {
......
Thread.sleep(properties.getSleepTime());
}
} catch (Exception e) {
logger.warn(e.getMessage());
setChanged(); // 捕獲到異常,線程結(jié)束鳞绕。標(biāo)記 改變, 只有標(biāo)記后才能通知到觀察者
notifyObservers(); // 通知觀察者
}
}
......
}