设计模式 Design Parttern ——建造者模式 Builder

 

设计模式 Design Parttern ——建造者模式 Builder

http://blog.csdn.net/leeidea

 

 

1:头文件

#ifndef _BULDER_H_VANEY_ #define _BULDER_H_VANEY_ #include using namespace std; /****************************************************************** 名称 :builder.h 版本 :1.00 描述 :演示建造者模式的概念 作者 :[email protected] http://blog.csdn.net/leeidea 日期 :2010年10月13日 版权 :[email protected] http://blog.csdn.net/leeidea ******************************************************************/ /* 官方解释:The Builder pattern separates the construction of a complex object from its representation, so the same construction process can create different representations. 我的理解:抽象工厂是返回一些方法的集合(C++中即返回一个具体类的函数指针),创建者模式是 返回创建好的东西。 我的应用:目前项目中好像无此用法。是否可以找出一些模块的相同点,然后将这些相同的过程做 作为一个Builder的过程。 */ //建造者基类 class CBuilder { public: CBuilder() { cout << "CBuilder()" << endl; } virtual ~CBuilder() { cout << "~CBuilder()" << endl; } public: virtual int BuilderPartA(void) = 0; virtual int BuilderPartB(void) = 0; }; //建造者具体类 class CBuilderCar : public CBuilder { public: CBuilderCar() { cout << "CBuilderCar()" << endl; } virtual ~CBuilderCar() { cout << "~CBuilderCar()" << endl; } public: virtual int BuilderPartA(void) { cout << "CBuilderCar BuilderPartA" << endl; return 1; } virtual int BuilderPartB(void) { cout << "CBuilderCar BuilderPartB" << endl; return 1; } }; //建造者具体类 class CBuilderBus : public CBuilder { public: CBuilderBus() { cout << "CBuilderBus()" << endl; } virtual ~CBuilderBus() { cout << "~CBuilderBus()" << endl; } public: virtual int BuilderPartA(void) { cout << "CBuilderBus BuilderPartA" << endl; return 1; } virtual int BuilderPartB(void) { cout << "CBuilderBus BuilderPartB" << endl; return 1; } }; //建造者使用者 class CDirector { CBuilder* _builder; public: CDirector(CBuilder* builder) { _builder = builder; cout << "CDirector()" << endl; } virtual ~CDirector() { if(!_builder) delete _builder; _builder = NULL; cout << "~CDirector()" << endl; } public: int Build(void) { if(_builder) { //创建各个部分 _builder->BuilderPartA(); _builder->BuilderPartB(); return 1; } return 0; } }; #define VANEY_API //用户 extern "C" VANEY_API int UsingBD(); #endif

 

2:源文件

#include "Builder.h" VANEY_API int UsingBD() { //创建Car CBuilderCar* car = new CBuilderCar(); CDirector* director_car = new CDirector(car); director_car->Build(); //创建Bus CBuilderBus* bus = new CBuilderBus(); CDirector* director_bus = new CDirector(bus); director_bus->Build(); return 1; }

 

3:使用文件main.c

#include "Builder.h" VANEY_API int UsingBD() { //创建Car CBuilderCar* car = new CBuilderCar(); CDirector* director_car = new CDirector(car); director_car->Build(); //创建Bus CBuilderBus* bus = new CBuilderBus(); CDirector* director_bus = new CDirector(bus); director_bus->Build(); return 1; }

你可能感兴趣的:(设计模式)