C++ 代理类的实现

#include <string>
#include <iostream>
class Vehicle
{
protected:
    std::string name;
public:
    Vehicle():name("noName"){};
    Vehicle(const std::string& s):name(s){};
    virtual Vehicle * clone() const = 0;
    virtual void run() const = 0;
    virtual ~Vehicle(){std::cout <<" Base destruction!" << std::endl;}
};
class Car :public Vehicle
{
public:
    Car():Vehicle("car"){};
    Car(const std::string & s):Vehicle(s){};
    void run() const{std::cout << name << " is running" << std::endl;}
    Car * clone()const {return new Car("car");}
    ~Car(){std::cout <<" Car destruction!" << std::endl;}
};
class Truck: public Vehicle
{
public:
    Truck():Vehicle("truck"){};
    Truck(const std::string & s):Vehicle(s){};
    void run() const{std::cout << name << " is running" << std::endl;}
    Truck * clone()const {return new Truck("truck");}
    ~Truck(){std::cout <<" Truck destruction!" << std::endl;}
};
class AirPlane:public Vehicle
{
public:
    AirPlane():Vehicle("airPlane"){};
    AirPlane(const std::string & s):Vehicle(s){};
    void run() const{std::cout << name << " is running" << std::endl;}
    AirPlane * clone()const {return new AirPlane("airplane");}
    ~AirPlane(){std::cout <<" AirPlane destruction!" << std::endl;}
};
class VehicleProxy
{
private:
    Vehicle *ve;
public:
    VehicleProxy():ve(0){}
    VehicleProxy(const Vehicle & v):ve(v.clone()){}
    VehicleProxy(const VehicleProxy &vs):ve(vs.ve ? vs.ve->clone() : 0){}
    VehicleProxy & operator = (const VehicleProxy & vs);
    ~VehicleProxy(){delete ve;}
    void run(){if(ve != 0) ve->run();}
};
VehicleProxy & VehicleProxy::operator = (const VehicleProxy & vs)
{
    if(&vs != this)
    {
        delete ve;
        ve = vs.ve->clone();
    }
    return *this;
}
int main()
{
	VehicleProxy vehicleProxy[3];
    Car car;
    Truck truck;
    AirPlane airPlane;
    vehicleProxy[0] = car;
    vehicleProxy[1] = truck;
    vehicleProxy[2] = airPlane;
    for(int i = 0; i < 3; i++)
        vehicleProxy[i].run();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值