设计模式

来源:互联网 发布:上海数据交易中心面试 编辑:程序博客网 时间:2024/05/29 21:31

外观模式(Façade Pattern)

基本概念:

外观模式的主用工作室屏蔽实际的实例化操作,利用一个界面类(暂且称为界面类,是直接针对客户的类,不是真正的UI类)来生成一个个需要的对象。外观模式非常像工厂模式,不同点是外观模式的界面类中已经明确了要创建的实例对象。

什么时候用到外观模式:

对于用户来说,只需通过某个接口获得实例对象,而并不需要知道某个类的具体创建的过程。如一个系统(system)有很多子系统(subsystem),我们使用的时候只需要知道系统如何使用和运行,而不需要知道子系统是如何创建和运行的。

举个栗子:

举个开汽车的例子(很多时候都是拿汽车说事,没办法,对汽车太感兴趣了,还做了几年的汽车电子方面的开发)。我们开汽车的时候,只需要拧一下钥匙(或者按一下START,越来越多的一键启动),此时汽车的一次启动电动机,通过电动机带动内燃机启动,会启动汽车的大灯系统,会启动中控仪表灯,显示当前参数,会启动一些辅助性自检功能,检测有没有关好门,有没有系安全带等。当然还有很多更高级的功能。

上代码:

//汽车各子系统

//H

#pragma once

#include <iostream>

#include <string>

#include <assert.h>

 

 

using namespace std;

 

class subsystem

{

public:

   subsystem(void);

   ~subsystem(void);

   virtual void start() = 0;

};

 

class motor: public subsystem

{

public:

   motor(){}

   ~motor(){}

   void start();

};

 

class internalCombustionEngine: public subsystem

{

public:

   internalCombustionEngine(){}

   ~internalCombustionEngine(){}

   void start();

};

 

class selfCheck: public subsystem

{

public:

   selfCheck(){}

   ~selfCheck(){}

   void start();

};

 

class lights: public subsystem

{

public:

   lights(){}

   ~lights(){}

   void start();

};

//CPP

#include "subsystem.h"

 

subsystem::subsystem(void)

{

}

 

subsystem::~subsystem(void)

{

}

 

void motor::start()

{

   cout<<"startmotor"<<endl;

}

 

void internalCombustionEngine::start()

{

   cout<<"startinternal combustion engine"<<endl;

}

 

void selfCheck::start()

{

   cout<<"startself check"<<endl;

}

 

void lights::start()

{

   cout<<"startlights"<<endl;

}

//汽车系统

//H

#pragma once

#include "subsystem.h"

 

class carsystem

{

public:

   carsystem(void);

   ~carsystem(void);

   void start();

private:

   motor* _motor;

   internalCombustionEngine* _internalCombustionEngine;

   selfCheck* _selfCheck;

   lights* _lights;

};

//CPP

#include "carsystem.h"

 

carsystem::carsystem(void)

{

   _motor = new motor();

   _internalCombustionEngine =new internalCombustionEngine();

   _selfCheck = new selfCheck();

   _lights = new lights();

}

 

carsystem::~carsystem(void)

{

   if(_motor!=NULL)

      delete _motor;

   if(_internalCombustionEngine!=NULL)

      delete _internalCombustionEngine;

   if(_selfCheck!=NULL)

      delete _selfCheck;

   if(_lights!=NULL)

      delete _lights;

}

 

void carsystem::start()

{

   _motor->start();

   _internalCombustionEngine->start();

   _selfCheck->start();

   _lights->start();

   cout<<"CARREADY"<<endl;

}

//测试

#include "carsystem.h"

 

int main()

{

   carsystem* carbenz = new carsystem();

   carbenz->start();

 

   return 0;

}

 

 

 

 

 

原创粉丝点击