大话设计模式--外观模式 Facade -- C++实现实例

1.  外观模式: 为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这个子系统更加容易使用。

 

外观模式的使用场合:

A: 设计初期阶段,应该要有意识的将不同的两个层分离。

B: 在开发阶段,子系统往往由于不断的重构演化而变得越来越复杂,

C: 在维护一个遗留的大系统时,可能这个系统已经非常难以维护和扩展。

将 和复杂的子系统打交道的任务交给 Facade, 客户端只需要调用简洁的Facade方法。

 

实例:

subsystem.h    subsystem.cpp

#ifndef SUBSYSTEM_H
#define SUBSYSTEM_H

#include<iostream>
using namespace std;

class SubSystemA
{
public:
    void MethodA();
};

class SubSystemC
{
public:
    void MethodC();
};

class SubSystemB
{
public:
    void MethodB();
};

#endif // SUBSYSTEM_H
#include "subsystem.h"

void SubSystemA::MethodA()
{
    cout << "SubSystem MethodA" << endl;
}

void SubSystemB::MethodB()
{
    cout << "SubSystem MethodB" << endl;
}

void SubSystemC::MethodC()
{
    cout << "SubSystem MethodC" << endl;
}


facade.h -- facade.cpp外衣

#ifndef FACADE_H
#define FACADE_H

#include "subsystem.h"

class Facade
{
public:
    Facade();
    void MethodA();
    void MethodB();

private:
    SubSystemA *subA;
    SubSystemB *subB;
    SubSystemC *subC;
};

#endif // FACADE_H
#include "facade.h"

Facade::Facade()
{
    subA = new SubSystemA;
    subB = new SubSystemB;
    subC = new SubSystemC;
}

void Facade::MethodA()
{
    cout << "Facade MethodA" << endl;
    subA->MethodA();
    subC->MethodC();
}

void Facade::MethodB()
{
    cout << "Facade MethodB" << endl;
    subB->MethodB();
    subC->MethodC();
}

 

main.cpp

#include <iostream>
#include "facade.h"
using namespace std;

int main()
{
    cout << "Facade test!" << endl;

    Facade facade;
    facade.MethodA();
    facade.MethodB();

    return 0;
}





 

 

 

 

posted @ 2013-10-09 15:08  今晚打酱油_  阅读(184)  评论(0编辑  收藏  举报