代理类
代理类
(好久没写了,这段时间更迷茫了,不知道该做些什么。)
——《C++沉思录》第五章 代理类
#include <iostream> using namespace std; // 基类 class Vehicle { private: public: Vehicle() {} virtual ~Vehicle() {} virtual double weight() const = 0; virtual void start() = 0; virtual Vehicle* copy() const = 0; }; // 派生类 class Truck : public Vehicle { private: public: Truck() {} virtual~Truck() {} virtual double weight() const; virtual void start(); virtual Vehicle* copy() const; }; double Truck::weight() const { return 0.0; } void Truck::start() { return; } Vehicle* Truck::copy() const { return new Truck(*this); } // 代理类 class VehicleSurrogate { private: Vehicle* vp; public: VehicleSurrogate(); VehicleSurrogate(const Vehicle&); ~VehicleSurrogate(); VehicleSurrogate(const VehicleSurrogate&); VehicleSurrogate& operator = (const VehicleSurrogate&); // 来自被代理类的操作 double weight() const; void start(); }; VehicleSurrogate::VehicleSurrogate() : vp(0) {} VehicleSurrogate::VehicleSurrogate(const 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) { throw "Empty VehicleSurrogate.weight()"; } return vp->weight(); } void VehicleSurrogate::start() { if (vp == 0) { throw "Empty VehicleSorrogate.start()"; } return vp->start(); } int main() { VehicleSurrogate parking_lot[1000]; Truck t; int num_vehicles = 0; parking_lot[num_vehicles++] = t; parking_lot[num_vehicles++] = VehicleSurrogate(t); return 0; }
代理类只有一个,其可以代理继承层次中的任意一个类。代理类不存在继承层次。另外,可以进一步学习设计模式之代理模式,从而更进一步理解代理的思想和原理。
(完)
文档信息
·版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0
·博客地址:http://www.cnblogs.com/unixfy
·博客作者:unixfy
·作者邮箱:goonyangxiaofang(AT)163.com
·如果你觉得本博文的内容对你有价值,欢迎对博主 小额赞助支持
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步