这篇文章给大家分享的是有关C++设计模式之Proxy模式的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
代理模式很容易理解,就是代替别人去做某一件事,打个比方,我们需要买水果,一般是去超市或者水果店买水果,很少有人去果园买水果,果园是生产水果的地方,但很少出售水果,在这里,水果店,超市就成了代理。
首先定义一个抽象类,提供所有的函数接口。
1.定义卖水果的抽象类,也就是接口,果园与超市都要继承这个类。
#pragma once
class CSellFruits//定义一个抽象类
{
public:
CSellFruits(void);
virtual ~CSellFruits(void);
virtual void sellapple()=0; //定义接口,卖苹果
virtual void sellorange()=0;//定义接口,卖橘子
};
#include "SellFruits.h"
CSellFruits::CSellFruits(void)
{
}
CSellFruits::~CSellFruits(void)
{
}
2.定义具体类,也就是果园类,果园生产水果,但是一般不买水果
#pragma once
#include "sellfruits.h"
#include <stdio.h>
class COrchard :
public CSellFruits
{
public:
COrchard(void);
virtual ~COrchard(void);
virtual void sellapple();
virtual void sellorange();
};
#include "Orchard.h"
COrchard::COrchard(void)
{
}
COrchard::~COrchard(void)
{
}
void COrchard::sellapple()
{
printf("Sell apple\n");
}
void COrchard::sellorange()
{
printf("Sell orange\n");
}
3.定义代理类,代理卖水果的类
#pragma once
#include "sellfruits.h"
#include "Orchard.h"
#include <stdio.h>
class CProcySellFruits :
public CSellFruits
{
public:
CProcySellFruits(void);
virtual ~CProcySellFruits(void);
virtual void sellapple();
virtual void sellorange();
private:
CSellFruits *p_SellFruits; //传入接口对象
};
#include "ProcySellFruits.h"
CProcySellFruits::CProcySellFruits(void):p_SellFruits(NULL)
{
}
CProcySellFruits::~CProcySellFruits(void)
{
}
void CProcySellFruits::sellapple()
{
if(this->p_SellFruits==NULL)
{
this->p_SellFruits=new COrchard(); //用被代理的类实例化
}
this->p_SellFruits->sellapple();//代理果园卖苹果
}
void CProcySellFruits::sellorange()
{
if(this->p_SellFruits==NULL)
{
this->p_SellFruits=new COrchard(); //用被代理的类实例化
}
this->p_SellFruits->sellorange();//代理果园卖橘子
}
4.实际调用
CProxySellFruits* p=new CProxySellFruits(); //用代理类卖水果
p->SellApple();
p->SellOrange();
感谢各位的阅读!关于“C++设计模式之Proxy模式的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。