一、代理模式
二、虚代理
#include <iostream>
#include <unistd.h>
using namespace std;
class Text
{
public:
void showText()
{
cout << "good sentence" << endl;
}
};
class ImageSubject
{
public:
virtual void showImage() = 0;
};
class BigImage : public ImageSubject
{
public:
BigImage()
{
sleep(6);
cout << "load done, show" << endl;
}
void showImage()
{
cout << "Image is shown" << endl;
}
};
class ProxyImage : public ImageSubject
{
public:
ProxyImage()
{
bi = NULL;
}
void showImage()
{
if (bi == NULL) bi = new BigImage;
bi->showImage();
}
private:
BigImage * bi;
};
class Doc
{
public:
Doc()
{
t = new Text;
pi = new ProxyImage;
}
void show()
{
t->showText();
pi->showImage();
}
private:
Text * t;
ProxyImage * pi;
};
int main()
{
Doc d;
d.show();
return 0;
}
三、智能代理
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
A()
{
cout << "A()" << endl;
}
~A()
{
cout << "~A()" << endl;
}
void dis()
{
cout << "auto_ptr" << endl;
}
};
class SmartPointer
{
public:
SmartPointer(A *pa) : _pa(pa) {}
~SmartPointer()
{
delete _pa;
}
A* &operator->()
{
return _pa;
}
A &operator*()
{
return *_pa;
}
private:
A * _pa;
};
// ap是对象A的代理
void func()
{
// auto_ptr<A> ap(new A);
// ap->dis();
SmartPointer sp(new A);
sp->dis();
(*sp).dis();
}
int main()
{
// A a;
// a.dis();
func();
return 0;
}