设计模式——观察者众( 三 )


定义线程任务:
public class MyThread implements Runnable, Subject {private List obs;private String res;MyThread() {obs = new ArrayList<>();}@Overridepublic void run() {//TODO 执行线程任务模拟执行任务延时 后获取任务结果try {TimeUnit.SECONDS.sleep(1);res = "号外号外,又到周末了,放假啦 。。。。。。嗨起来";} catch (InterruptedException e) {e.printStackTrace();}// 通知观察者(们)notifyObserver();}@Overridepublic void registerObserver(ICallback callback) {obs.add(callback);}@Overridepublic void removeObserver(ICallback callback) {obs.remove(callback);}@Overridepublic void notifyObserver() {//通知观察者for (ICallback callback : obs) {callback.update(res);}}}
观察者们:
public class Tom implements ICallback {@Overridepublic void update(String result) {System.out.println("Tom received:"+result);}} 。。。。public class Rubi implements ICallback {@Overridepublic void update(String result) {System.out.println("Rubi received:"+result);}}
测试:
public class Test {public static void main(String[] args) {MyThread mt = new MyThread();mt.registerObserver(new Tom());// 注册 Tommt.registerObserver(new Rubi()); // 注册 Rubinew Thread(mt).start();// 在主线程中开启子线程任务}}
----------------执行结果--------------------------------------
Tom :号外号外,明天又放假了 。。。。。。嗨起来
Rubi :号外号外,明天又放假了 。。。。。。嗨起来

OVER !
转载于: