C++代理类是为了解决这样的问题: 容器通常只能包含一种类型的对象,所以很难在容器中存储对象本身。怎样设计一个c++容器,使它有能力包含类型不同而彼此相关的对象?
代理运行起来和他所代表的对象基本相同,但是允许将整个派生层次压缩在一个对象类型中。
- #include <iostream>
- using namespace std;
-
- class Vehicle
- {
- public:
- virtual double weight() const = 0;
- virtual Vehicle* copy() = 0;
- virtual ~Vehicle() {}
- };
-
- class AutoVehicle:public Vehicle
- {
- public:
- double weight() const
- {
- cout << "AutoVehicle weight" << endl;
- return 1;
- }
- Vehicle* copy()
- {
- return new AutoVehicle(*this);
- }
- };
-
- class RoadVehicle:public Vehicle
- {
- public:
- double weight() const
- {
- cout << "RoadVehicle weight" << endl;
- return 2;
- }
- Vehicle* copy()
- {
- return new RoadVehicle(*this);
- }
- };
-
- class VehicleSurrogate
- {
- public:
- VehicleSurrogate();
- VehicleSurrogate(Vehicle&);
- ~VehicleSurrogate();
- VehicleSurrogate(const VehicleSurrogate&);
- VehicleSurrogate& operator=(const VehicleSurrogate&);
- double weight() const;
- private:
- Vehicle *vp;
- };
- VehicleSurrogate::VehicleSurrogate():vp(0){}
-
- VehicleSurrogate::VehicleSurrogate(Vehicle &v):vp(v.copy()){}
- VehicleSurrogate::~VehicleSurrogate()
- {
- delete vp;
- }
-
- VehicleSurrogate::VehicleSurrogate(const VehicleSurrogate &v):vp(v.vp ? v.vp->copy() : 0){}
- VehicleSurrogate& VehicleSurrogate::operator=(const VehicleSurrogate &v)
- {
- if(this != &v)
- {
- delete vp;
- vp = (v.vp ? v.vp->copy() : 0);
- }
- return *this;
- }
- double VehicleSurrogate::weight() const
- {
- if(vp == 0)
- {
- cout << "empty VehicleSurrogate" << endl;
- }
- else
- {
- return vp->weight();
- }
- }
- int main()
- {
- VehicleSurrogate parking_lot[1000];
- AutoVehicle x;
- int num_vehicles = 0;
- parking_lot[num_vehicles++] = x;
- parking_lot[0].weight();
- RoadVehicle y;
- parking_lot[num_vehicles++] = VehicleSurrogate(y);
- parking_lot[1].weight();
- return 0;
- }
为了避免显示的处理内存分配,又能保持类Vehicle在运行时绑定。这里采用代理类技术,就是定义一个行为和Vehicle对象相似,而又潜在地表示所有继承自Vehicle类的对象的东西。每个Vehicle代理都代表某个继承自Vehicle类的对象。只要该代理关联着这个对象,该对象就肯定存在。
代理类的每个对象都代表另一个对象,该对象可以是位于一个完整继承层次中的任何类的对象。通过在容器中使用代理对象而不是对象本身的方式,就是代理类的精髓思想所在。