即Proxy Pattern,23种常用的面向对象软件的设计模式之一。代理模式的定义:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
class RealImage
{
int m_id;
public:
RealImage(int i)
{
m_id = i;
cout
<< " $$ ctor: " << m_id << '\n';
}
~RealImage()
{
cout << "
dtor: " << m_id << '\n';
}
void draw()
{
cout << "
drawing image " << m_id << '\n';
}
};
class ProxyImage
{
RealImage *m_the_real_thing;
int m_id;
static int s_next;
public:
ProxyImage() {
m_id =
s_next++;
m_the_real_thing = 0;
}
~Image() {
delete
m_the_real_thing;
}
void draw() {
if (!m_the_real_thing)
m_the_real_thing = new
RealImage(m_id);
m_the_real_thing->draw();//通过ProxyImage代理调用RealImage中的draw()
}
};
int Image::s_next = 1;
int main()
{
ProxyImage images[5];
int i = 0;
while(1)
{
cout <<
"Exit[0], image[1-5]: ";
cin >> i;
if (i == 0)
break;
images[i - 1].draw();
}
system("Pause");
};
Copyright 2011-2020 © MallocFree. All rights reserved.