论坛首页 编程语言技术论坛

C++设计模式之代理

浏览 3886 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-09-15  
C++设计模式之代理

废话少说,先奉上代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
class IKindwomen
{
public:
	
IKindwomen(void);
	
~IKindwomen(void);
	
virtual void makeEyesWithMan();
	
virtual void tlaWithMan();
};
class WangPo{
public:
	
WangPo(IKindwomen * pKindwomen);
	
~WangPo();
	
void makeEyesWithMan();
	
void tlaWithMan();
private:
	
IKindwomen * pKindwomen;
};
class PanJianLian:public IKindwomen{
public:
	
PanJianLian();
	
~PanJianLian();
	
virtual void makeEyesWithMan();
	
virtual void tlaWithMan();
};
class JiaShi:public IKindwomen{
public:
	
JiaShi();
	
~JiaShi();
	
virtual void makeEyesWithMan();
	
virtual void tlaWithMan();
};
WangPo::WangPo(IKindwomen * pKindwomen){
	
this->pKindwomen = pKindwomen;
}
WangPo::~WangPo(){
	
delete this->pKindwomen;
}
void WangPo::makeEyesWithMan(){
	
this->pKindwomen->makeEyesWithMan();
}
void WangPo::tlaWithMan(){
	
this->pKindwomen->tlaWithMan();
}

PanJianLian::PanJianLian(){}
PanJianLian::~PanJianLian(){}
void PanJianLian::makeEyesWithMan(){
	
cout<<"潘金莲抛媚眼!"<<endl;
}
void PanJianLian::tlaWithMan(){
	
cout<<"潘金莲谈恋爱!"<<endl;
}
JiaShi::JiaShi(){}
JiaShi::~JiaShi(){}
void JiaShi::makeEyesWithMan(){
	
cout<<"贾氏抛媚眼!"<<endl;
}
void JiaShi::tlaWithMan(){
	
cout<<"贾氏谈恋爱!"<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
	
WangPo* wangPo = new WangPo(new PanJianLian());
	
wangPo->makeEyesWithMan();
	
wangPo->tlaWithMan();
	
delete wangPo;
	
return 0;
}

先说类的设计,首先定义一个IKindwomen 类,声明虚函数:makeEyesWithMan(),tlaWithMan(),下面的JiaShi和PanJianLian类分别继承自IKindwomen 类
各自实现了上述连个成员方法。其次WangPo类声明了makeEyesWithMan(),tlaWithMan()和一个IKindwomen类型的私有成员变量。

在下面的main函数调用中,我们发现在我们调用makeEyesWithMan(),tlaWithMan()方法的时候是通过WangPo类的实例调用的,并未通过JiaShi和PanJianLian类的实例调用,在WangPo类的构造函数中入参数的类型决定了makeEyesWithMan(),tlaWithMan()函数的具体调用细节。通过上述的设计,实现了代理之功效,巧妙的通过WangPo类来管理西门庆的妹子们。此为C++ 之代理模式简单实现,望各位多多指教。
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics