zoukankan      html  css  js  c++  java
  • 代理类

    代理类

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

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

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

  • 相关阅读:
    20172332 2017-2018-2 《程序设计与数据结构》第五周学习总结
    ASL测试 课题测试博客
    20172332 2017-2018-2 《程序设计与数据结构》第四周学习总结
    大白话Docker入门(一)
    Hexo博客搭建全解
    代码查重工具sim
    virtual judge 本地部署方案
    POJ题目分类推荐 (很好很有层次感)
    解决Ubuntu下Sublime Text 3无法输入中文
    [pascal入门]数组
  • 原文地址:https://www.cnblogs.com/unixfy/p/3428644.html
Copyright © 2011-2022 走看看