程序最美(寻路)

你还在坚持练习你的技术吗?运动员天天训练,音乐家也会演练更难的曲章。你呢?

代理类

代理类

         (好久没写了,这段时间更迷茫了,不知道该做些什么。)

         ——《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;
}

         代理类只有一个,其可以代理继承层次中的任意一个类。代理类不存在继承层次。另外,可以进一步学习设计模式之代理模式,从而更进一步理解代理的思想和原理。

posted on 2013-11-18 01:38  unixfy  阅读(324)  评论(0编辑  收藏  举报

导航