设计模式-Proxy(结构型模式)

以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码

//Proxy.h

#pragma once
class Subject
{
public:
    virtual ~Subject();
    virtual void Request() = 0;
protected:
    Subject();
};

class ConcreateSubject:public Subject
{
public:
    ~ConcreateSubject();
    ConcreateSubject();
    void Request();
protected:
private:
};

class Proxy {
public:
    Proxy();
    Proxy(Subject* sub);
    ~Proxy();
    void Request();
protected:
private:
    Subject* _sub;
};

//Proxy.cpp

#include"Proxy.h"
#include<iostream>

Subject::Subject(){}
Subject::~Subject(){}
void Subject::Request()
{
    std::cout << "Subject Request" << std::endl;
}

ConcreateSubject::ConcreateSubject(){}
ConcreateSubject::~ConcreateSubject(){}
void ConcreateSubject::Request()
{
    std::cout << "ConcreateSubject Request" << std::endl;
}
Proxy::Proxy(){}
Proxy::Proxy(Subject* sub)
{
    _sub = sub;
}
void Proxy::Request()
{
    std::cout << "代理Proxy Request" << std::endl;
    _sub->Request();
}
Proxy::~Proxy()
{
    delete _sub;
}

//main.cpp

#include"Proxy.h"
#include<iostream>

int main(int args, char* argv)
{
    Subject* sub = new ConcreateSubject();
    Proxy* p = new Proxy(sub);
    p->Request();
    return 0;
}
posted @ 2019-12-21 21:50  fourmii  阅读(187)  评论(0编辑  收藏  举报