C++设计模式——门面模式(Facade)

定义

门面模式是比较常用的一种设计模式,在 GoF 《设计模式》书中,门面模式是这样定义的:
门面模式为子系统提供一组统一的接口,定义一组高层接口让子系统更易用。

门面模式也有的书叫外观模式, 它提供一个高层次的接口,让子系统更易于使用。门面模式用一个门面类来处理子系统的复杂关系,门面类提供简单的Api接口供客户端调用。

高内聚,松耦合。安全。

优点

减少系统的相互依赖
提高了灵活性
提高安全性

适用场景

解决易用性问题。为访问一系列复杂的子系统提供一个统一的、简单的入口,可以使用外观模式;
客户端与多个子系统之间存在很大依赖,但在客户端编程,又会增加系统耦合度,且使客户端编程复杂,可以使用外观模式。

角色

Facade(外观角色):外观角色可以知道多个相关子系统的功能,它将所有从客户端发来的请求委派给相应的子系统,传递给相应的子系统处理。
SubSystem(子系统角色):子系统是一个类,或者由多个类组成的类的集合,它实现子系统具体的功能。 

代码示例


class ILetterProcess
{
public:
    ILetterProcess(void);
    virtual ~ILetterProcess(void);
    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(void);
    ~CLetterProcessImpl(void);

    void WriteContext(string context)    { cout << "填写信的内容... ..." << endl;}
    void FillEnvelope(string address)    { cout << "填写收件人地址及姓名... ..." << endl;}
    void LetterIntoEnvelope()     { cout << "把信放到信封中..." << endl;}
    void SendLetter()      { cout << "邮递信件..." << endl; }
};

 
class CModenPostOffice
{
public:
    CModenPostOffice(void){
         this->m_pLetterProcess = new CLetterProcessImpl();
         this->m_pLetterPolice = new CLetterPolice();
    }
    ~CModenPostOffice(void){
         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;  //Facade
    string context = "Hello, It's me, do you know who I am? I'm your old lover. I'd like to ... ...";
    string address = "Happy Road No. 666, Beijing City, China";
    modenPostOffice.SendLetter(context, address);
}
void DoItMyself()
{
    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 _tmain(int argc, _TCHAR* argv[])
{
    DoItByPostOffice();   //使用门面模式包装复杂的逻辑,方便子系统调用
    DoItMyself();

    return 0;
}

Facade类提供简单的接口给用户调用,其内部处理复杂的调用

应用

Socket是个典型的⻔面模式,它接口内部处理复杂的TCP/IP协议族调用,为用户提供一套各个跨平台的统一的简单的调用接口,让Socket去组织数据,以符合指定的协议。Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是⼀组接口。

猜你喜欢

转载自blog.csdn.net/panjunnn/article/details/108769722
今日推荐