一,普通代理模式
代理模式也比較容易理解,但是其用途不是很好理解了。
設計模式中運用了物件導向程式設計語言的重要特性:封裝、繼承、多態,真正領悟設計模式的精髓是可能一個漫長的過程,需要大量實踐經驗的積累。-------我還有很長的路要走了。
二 代理模式的使用
為其他對象提供一種代理以控制對這個對象的訪問。 其應用情境有:
1 遠程代理。
2. 虛擬代理,是根據需要建立開銷很大的對象時,通過它來存放執行個體化需要很長時間的真實對象。這樣可以達到效能最優,如當開啟html網頁時,需要很快開啟。但當網頁類執行“開啟”操作時,遇到圖片,就需要等待完成再進行。但是用代理模式,我們可以先儲存這樣一個圖片的代理(存放了,與圖片相同大小的尺寸),然後直接預留位置。等文字全部開啟,再進行“開啟圖片”的操作。
其應用中還有auto_ptr。
在這個例子屬於虛代理的情況,下面給兩個智能引用的例子。一個是C++中的auto_ptr,另一個是smart_ptr。自己實現了一下。先給出auto_ptr的代碼實現:
template<class T> class auto_ptr { public: explicit auto_ptr(T *p = 0): pointee(p) {} auto_ptr(auto_ptr<T>& rhs): pointee(rhs.release()) {} ~auto_ptr() { delete pointee; } auto_ptr<T>& operator=(auto_ptr<T>& rhs) { if (this != &rhs) reset(rhs.release()); return *this; } T& operator*() const { return *pointee; } T* operator->() const { return pointee; } T* get() const { return pointee; } T* release() { T *oldPointee = pointee; pointee = 0; return oldPointee; } void reset(T *p = 0) { if (pointee != p) { delete pointee; pointee = p; } } private: T *pointee; };
3.安全代理,用來控制真實對象訪問是的許可權。
4.智能引用。
我們知道C++中沒有記憶體回收機制,可以通過智能指標來彌補,下面給出智能指標的一種實現,採用了引用計數的策略。
template <typename T>class smart_ptr{public: smart_ptr(T *p = 0): pointee(p), count(new size_t(1)) { } //初始的計數值為1smart_ptr(const smart_ptr &rhs): pointee(rhs.pointee), count(rhs.count) { ++*count; } //拷貝建構函式,計數加1~smart_ptr() { decr_count(); } //析構,計數減1,減到0時進行記憶體回收,即釋放空間 smart_ptr& operator= (const smart_ptr& rhs) //重載賦值操作符{//給自身賦值也對,因為如果自身賦值,計數器先減1,再加1,並未發生改變++*count; decr_count(); pointee = rhs.pointee; count = rhs.count; return *this; } //重載箭頭操作符和解引用操作符,未提供指標的檢查 T *operator->() { return pointee; } const T *operator->() const { return pointee; } T &operator*() { return *pointee; } const T &operator*() const { return *pointee; }size_t get_refcount() { return *count; } //獲得引用計數器值private: T *pointee; //實際指標,被代理 size_t *count; //引用計數器void decr_count() //計數器減1{if(--*count == 0) {delete pointee;delete count;}}};
以上文章有摘抄,來自http://blog.csdn.net/wuzhekai1985/article/details/6669219