初步認(rèn)知
觀察者模式:是一種單項(xiàng)的發(fā)布/訂閱的廣播模式频鉴。其實(shí)缺厉,簡(jiǎn)單來(lái)講就一句話:當(dāng)一個(gè)對(duì)象變化時(shí)歼狼,其它依賴該對(duì)象的對(duì)象都會(huì)收到通知,并且隨著變化鹿榜!對(duì)象之間是一種一對(duì)多的關(guān)系施敢。
簡(jiǎn)易架構(gòu)
實(shí)例分析
觀察者接口:
public interface Observe {
public void invoke(String message);
}
兩個(gè)觀察者實(shí)現(xiàn)類:
public class ObserveImpl1implements Observe {
@Override
? ? public void invoke(String message) {
System.out.println("ObserveImpl1 is executing now!the message is :"+message);
? ? }
}
public class ObserveImpl2implements Observe {
@Override
? ? public void invoke(String message) {
System.out.println("ObserveImpl2 is executing now,the message is :"+message);
? ? }
}
發(fā)布者接口:
public interface Publish {
/* *
添加觀察者
*/
? ? public void add(Observe obv);
? ? /* *
刪除觀察者
*/
? ? public void del(Observe obv);
? ? /**
*通知所有觀察者
*/
? ? public void notifyAllObverves(String notifyMessage);
? ? /**
* 自身操作方法
*/
? ? public void epration(String messge);
}
發(fā)布者抽象類:
/**
* 此抽象類主要用于對(duì)觀察者進(jìn)行管理
*/
public abstract class PublishImplimplements Publish
{
//在發(fā)布者中心的觀察者管理列表
? ? private Vectorobserves =new Vector();
? ? /**
* 添加觀察者
? ? * @param obv
? ? */
? ? @Override
? ? public void add(Observe obv) {
observes.add(obv);
? ? }
/**
* 刪除觀察者
? ? * @param obv
? ? */
? ? @Override
? ? public void del(Observe obv) {
observes.remove(obv);
? ? }
/**
* 給所有觀察者發(fā)布通知
? ? * @param notifyMessage
? ? */
? ? @Override
? ? public void notifyAllObverves(String notifyMessage) {
Enumeration? elements =observes.elements();
? ? ? while(elements.hasMoreElements()){
elements.nextElement().invoke(notifyMessage);
? ? ? }
}
}
發(fā)布者實(shí)現(xiàn)類:
public class MyPublishextends PublishImpl {
@Override
? ? public void epration(String messge) {
System.out.println("the operation method is starting now!");
? ? ? ? notifyAllObverves(messge);
? ? }
}
觀察模式測(cè)試類:
public class TestOfObserve {
public static void main(String[] args) {
Observe ob1 =new ObserveImpl1();
? ? ? ? Observe ob2 =new ObserveImpl2();
? ? ? ? MyPublish publish =new MyPublish();
? ? ? ? publish.add(ob1);
? ? ? ? publish.add(ob2);
? ? ? ? System.out.println("model of observe start now!");
? ? ? ? /**
* 發(fā)送第一個(gè)通知
*/
? ? ? ? String first ="天亦有情天亦老";
? ? ? ? publish.epration(first);
? ? ? ? /**
* 發(fā)送第二個(gè)通知
*/
? ? ? ? String second ="人間正道是滄桑";
? ? ? ? publish.epration(second);
? ? }
}
執(zhí)行結(jié)果
model of observe start now!
the operation method is starting now!
ObserveImpl1 is executing now!the message is :天亦有情天亦老
ObserveImpl2 is executing now,the message is :天亦有情天亦老
the operation method is starting now!
ObserveImpl1 is executing now!the message is :人間正道是滄桑
ObserveImpl2 is executing now,the message is :人間正道是滄桑
總結(jié)
一個(gè)發(fā)布者發(fā)布了兩次通知,兩個(gè)觀察者都實(shí)時(shí)接收到了相應(yīng)的通知信息并且隨著通知的變化進(jìn)行實(shí)時(shí)的響應(yīng)辐脖。
這種模式觀察者必須注冊(cè)到發(fā)布者管理中心饲宛,由發(fā)布者中心統(tǒng)一管理(維護(hù)所有觀察者,也就是增刪改查等以及發(fā)布通知操作)
這種模式在程序設(shè)計(jì)實(shí)踐中適合橫向的切面操作嗜价。