觀察者模式實現的 `釋出/訂閱` 模型
阿新 • • 發佈:2018-12-24
釋出者
package indi.lewis.pub;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
/**
* 釋出者
*
* @author xiaodongxu
* @see Observable
* @since 1.0
*/
public class Publish extends Observable implements Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
public void run() {
System.out.println("--------------------------------任務開始----------------------------------------");
try { int sleep = new Random().nextInt(1000);System.out.println(sleep);Thread.sleep(sleep); }
catch (InterruptedException e) {}//耗時任務
System.out.println("--------------------------------任務結束----------------------------------------" );
System.out.println("--------------------------------釋出者廣播訊息----------------------------------------");
this.setChanged();//標記已經發生改變
notifyObservers("釋出者推送資料");
}
}
訂閱者
package indi.lewis.sub;
import java.util.Observable;
import java.util.Observer;
/**
* 訂閱者
* @see Observer
* @author xiaodongxu
* @since 1.0
*/
public class Subscribe implements Observer{
private final String name;
public Subscribe(String name) {
this.name = name;
}
public void update(Observable o, Object arg) {
System.out.println("--------------------------------訂閱者收取訊息----------------------------------------");
System.out.println(name+":接收到釋出者的引數:"+arg);
}
}
測試類
package indi.lewis;
import indi.lewis.pub.Publish;
import indi.lewis.sub.Subscribe;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
/**
* 工作執行緒池
*/
private static final ExecutorService pool = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException {
Publish publish = new Publish();
//新增多個觀察者
for (int i = 0; i < 100; i++) {
Subscribe subscribe = new Subscribe("訂閱者:" + i);
publish.addObserver(subscribe);
}
//新增觀察者(訂閱)
pool.execute(publish);
}
}