现在的位置: 首页 > 综合 > 正文

设计模式(三) —-代理模式

2012年07月21日 ⁄ 综合 ⁄ 共 1790字 ⁄ 字号 评论关闭


一,普通代理模式

代理模式也比较容易理解,但是其用途不是很好理解了。


设计模式中运用了面向对象编程语言的重要特性:封装、继承、多态,真正领悟设计模式的精髓是可能一个漫长的过程,需要大量实践经验的积累。-------我还有很长的路要走了。

二 代理模式的使用

为其他对象提供一种代理以控制对这个对象的访问。 其应用场景有:

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)) { }  //初始的计数值为1
	smart_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

抱歉!评论已关闭.