#include<iostream>
#include<cstring>
#include<cassert>
using namespace std;
class Base{
public:
virtual int get()const = 0;
virtual void set() = 0;
virtual Base* copy()=0;
};
class A:public Base{
public:
A(){}
int get()const
{
cout<<"A get()"<<endl;
return 1;
}
void set()
{
cout<<"A set()"<<endl;
}
A(const A* o)
{
}
Base* copy()
{
return new A(*this);
}
};
class B:public Base{
public:
B(){}
int get()const
{
cout<<"B get()"<<endl;
return 1;
}
void set()
{
cout<<"B set()"<<endl;
}
B(const B* o)
{
}
Base* copy()
{
return new B(*this);
}
};
class C:public Base{
public:
C(){}
int get()const
{
cout<<"C get()"<<endl;
return 1;
}
void set()
{
cout<<"C set()"<<endl;
}
C(const C* o)
{
}
Base* copy()
{
return new C(*this);
}
};
class Proxy{
public:
Proxy();
Proxy(Base&);
~Proxy(){}
Proxy(const Proxy&);
Proxy& operator=(const Proxy&);
int get()const
{
assert(p!=0);
return p->get();
}
void set()
{
assert(p!=0);
p->set();
}
private:
Base *p;
};
Proxy::Proxy():p(0){}
Proxy::Proxy(Base& b):p(b.copy()){}
Proxy::Proxy(const Proxy& b)
{
p = b.p?b.p->copy():0;
}
Proxy& Proxy::operator=(const Proxy& b)
{
if(this!=&b){
delete p;
p = b.p?b.p->copy():0;
}
return *this;
}
int main()
{
int i=0;
Proxy slot[100];
A x;
slot[i++] = x;
B y;
slot[i++] = y;
C z;
slot[i++] = z;
while(i--)
{
slot[i].get();
slot[i].set();
cout<<endl;
}
return 0;
}
代理类的作用是能够将不同的类型的类放在一个容器里面,这里的容器就是Proxy,代理类
不同类是指都是通过一个基类派生出来的,在每个不同的派生类中,设置一个copy函数(主要的作用是:生成所属类的临时类,并且转换成基类类型)
在代理类里面设置一个基类的指针,用来存放不同的派生类。
所有基类的方法,必须在代理类里面实现,但是实现可以通过代理类的基类指针,调用基类的方法,从而动态的调用不同类型的方法。
主要的思想是:利用类的virtual机制,基类是纯虚函数,在派生类中实现具体的操作,然后通过copy一个派生类的临时对象,转换成基类的指针形式,并且保存在代理类的基类指针里面。