java和c++觀察者模式實現
阿新 • • 發佈:2018-11-17
觀察者模式是一種比較常用的設計模式,,採用介面,封裝類中動態變化的方法,定義物件間的依賴關係,一邊但一個物件狀態發生改變時,所有以來他的物件都發生改變。
簡單的說,就是一管多,即關鍵就是觀察者和被觀察者,學習這一部分看其他部落格這樣解釋,就是多個屌絲追一個白富美的模式,多個屌絲就是所謂的觀察者,白富美就是被觀察者,白富美將追他的屌絲存到她的準男友表中,要是白富美生氣,屌絲們都被通知到,然後想方設法討好白富美,讓其開心,要是白富美不喜歡那個屌絲了,就將其從準男友表中去掉。就大概這個意思。我對其理解是來源於java的解釋,看c++老師講課想了長時間沒想清楚,最後在網上看了java的實現,在理解的基礎上,用java實現了,讓人比較舒服!然後嘗試用c++來實現,c++真生硬,但是很強的語言!!!。
現在看程式碼吧,不扯淡了!!!
c++實現
#include<iostream> #include<string> #include<list> #include<stdio.h> using namespace std; //定義觀察者行為介面 class watcherInter{ public: void WatcherInter(){} virtual ~watcherInter(){} virtual void update(string str){} }; //介面實現 class watcher:watcherInter{ public: ~watcher(){} void update(string str){ //通知計數 static int i = 0 ; cout<<"men No."<<i<<" "<<str<<endl ; i++ ; } }; //被觀察者介面,在開發中可以進行新增更多的需求 class watchedInter{ public: virtual ~watchedInter(){ } virtual void add(){} virtual void remove(){} virtual void nidify(string str){} }; //被觀察者介面方法實現 class watched:watchedInter{ private: //觀察者連結串列 list<watcher*>ls ; string str; public: watched():str(NULL){} watched(string strs){ str =strs; } ~watched(){} //將觀察者加入到連結串列中 void add(watcher *ob){ ls.push_back(ob); } //更新通知資訊 void update(string strs){ str = strs; } //移除指定的觀察者 void remove(watcher*ob){ ls.remove(ob); } //將資訊通知給每個觀察者 void nodify(){ list<watcher*>::iterator iter = ls.begin(); for(iter;iter!=ls.end();iter++) (*iter)->update(str); } }; int main(){ //在main函式中只需建立一個被觀察者,多個觀察者 watched *ww = new watched("hello,sir"); watcher *w1 = new watcher(); watcher *w2 = new watcher(); watcher *w3 = new watcher(); ww->add(w1); ww->add(w2); ww->add(w3); ww->nodify(); cout<<"-----------------------------------------"<<endl; ww->update("you are so handsome!!!"); ww->nodify(); delete ww; delete w1; delete w2; delete w3; }
執行截圖:
java實現
import java.util.ArrayList; import java.util.List; interface WatcherInter{ public void update(String str); } class Watcher implements WatcherInter{ public void update(String str) { System.out.println(str); } } interface WatchedInter{ public void addWatch(Watcher ww); public void removeWatch(Watcher ww); public void nodifyWatch(String str); } class Watched implements WatchedInter{ private List<Watcher> ll = new ArrayList<Watcher>(); public void addWatch(Watcher ww) { ll.add(ww); } public void removeWatch(Watcher ww) { ll.remove(ww); } public void nodifyWatch(String str) { int i = 1 ; for(Watcher s : ll ) { s.update("Watch NO "+i+" "+str); i++ ; } } } public class Observer { public static void main(String []args) { Watched wed = new Watched(); Watcher wh = new Watcher(); Watcher wh1 = new Watcher(); Watcher wh2 = new Watcher(); wed.addWatch(wh); wed.addWatch(wh1); wed.addWatch(wh2); wed.nodifyWatch("你好!!!"); wed.nodifyWatch("hello!"); } }
觀察者實現了面向介面程式設計,而不是面向實現程式設計,使得程式可複用性更高,在實際軟體開發中,實現了程式可擴充套件,在不改變程式架構和功能的情況下,提高了程式碼的耦合性,在需求不斷變化的情況下只需在程式中作微小的改動。