解释说明:
基本上每个软件系统都会用到的模式,其含义是为子系统中的一组接口提供一个一致的界面, 模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。简单说,就是将复杂的逻辑封装起来,对外公开简单的接口,由客户程序调用。
以收发信件和警察检查实例为例
说明:邮局对外只有一个窗口,接收信件内容和邮件地址。对内调用邮件处理的4个函数。将复杂逻辑封装在邮局的里面,当需要增加警察来检查信件时,只需在邮局内增加警察检查信件的方法。
注意:将复杂逻辑封装起来,对外只有一个简单的接口。
例子:信号处理过程。
CModenPostOffice封装了复杂的处理逻辑,对外只有SendLetter这个函数接口。使客户程序容易了解到想要做什么,应该告诉邮局什么内容,邮局才能正确的工作。
参考链接:https://www.cnblogs.com/wanggary/category/294620.html
#include <iostream>
using namespace std;
//说明:邮局对外只有一个窗口,接收信件内容和邮件地址。
//对内调用邮件处理的4个函数。将复杂逻辑封装在邮局的里面,
//当需要增加警察来检查信件时,只需在邮局内增加警察检查信件的方法。
//注意:将复杂逻辑封装起来,对外只有一个简单的接口。
//抽象信件处理类
class ILetterProcess
{
public:
ILetterProcess(){}
virtual ~ILetterProcess(){}
virtual void WriteContext(string context) = 0;
virtual void FillEnvelope(string address) = 0;
virtual void LetterIntoEnvelope() = 0;
virtual void SendLetter() = 0;
};
//信件处理实现类
class CLetterProcessImpl :public ILetterProcess
{
public:
CLetterProcessImpl(){}
~CLetterProcessImpl(){}
void WriteContext(string context)
{
cout << "填写信的内容..." << endl;
}
void FillEnvelope(string address)
{
cout << "填写收件人地址及姓名..." << endl;
}
void LetterIntoEnvelope()
{
cout << "把信放到信封中..." << endl;
}
void SendLetter()
{
cout << "邮递信件..." << endl;
}
};
//警察检查信件类
class CLetterPolice
{
public:
CLetterPolice(){}
~CLetterPolice(){}
void checkLetter(ILetterProcess* pLetterProcess)
{
cout << "检查信件,此处省略一万字..." << endl;
return;
}
};
//邮局处理信件类
class CModenPostOffice
{
public:
CModenPostOffice()
{
this->m_pLetterProcess = new CLetterProcessImpl;
this->m_pLetterPolice = new CLetterPolice();
}
~CModenPostOffice()
{
delete m_pLetterProcess;
delete m_pLetterPolice;
}
void SendLetter(string context, string address)
{
//写信
m_pLetterProcess->WriteContext(context);
//写好信封
m_pLetterProcess->FillEnvelope(address);
//警察要检查信件了
m_pLetterPolice->checkLetter(m_pLetterProcess);
//把信件放到信封中
m_pLetterProcess->LetterIntoEnvelope();
//邮递信件
m_pLetterProcess->SendLetter();
}
private:
ILetterProcess* m_pLetterProcess;
CLetterPolice* m_pLetterPolice;
};
void doitbypostoffice()
{
CModenPostOffice modenpostoffice;
string context = "Hello, It's me, do you know who I am? I'm your old lover. I'd like to ... ...";
string adress = "Happy Road No. 666, Beijing City, China";
modenpostoffice.SendLetter(context, adress);
}
void doityourself()
{
char my[] = "i do it by myself.";
cout << my<<endl << endl;
ILetterProcess* pLetterProcess = new CLetterProcessImpl;
pLetterProcess->WriteContext("Hello, It's me, do you know who I am? I'm your old lover. I'd like to ... ..");
pLetterProcess->FillEnvelope("Happy Road No. 666, Beijing City, China.");
pLetterProcess->LetterIntoEnvelope();
pLetterProcess->SendLetter();
delete pLetterProcess;
}
int main()
{
doitbypostoffice();
doityourself();
return 0;
}