构造者模式。外部场景如果需要一个汽车类,它不需要关心如何构造,它只需要告诉Director需要什么,就可以从Director获得。
如:CDirector(IBuilder* aBuilder);
场景告诉Director它需要用什么类型的Builder来构造,然后就可以用Create()获得所创建的对象。
具体的构造由具体的Builder负责,当我们想变换创建方法时,变换传递的Builder实例就可以了。
C++示例
IBuilder.h
1 #pragma once 2 #include <string> 3 using namespace std; 4 5 class IBuilder 6 { 7 public: 8 IBuilder(void); 9 ~IBuilder(void); 10 public: 11 virtual void BuildA(const string& str)=0; 12 virtual void BuildB(const string& str)=0; 13 };
IBuilder.cpp
1 #include "IBuilder.h" 2 3 4 IBuilder::IBuilder(void) 5 { 6 } 7 8 9 IBuilder::~IBuilder(void) 10 { 11 }
Builder.h
1 #pragma once 2 #include "ibuilder.h" 3 4 class CBuilder : 5 public IBuilder 6 { 7 public: 8 CBuilder(void); 9 ~CBuilder(void); 10 public: 11 void BuildA(const string& str); 12 void BuildB(const string& str); 13 };
Builder.cpp
1 #include "Builder.h" 2 #include <iostream> 3 4 CBuilder::CBuilder(void) 5 { 6 } 7 8 9 CBuilder::~CBuilder(void) 10 { 11 } 12 13 void CBuilder::BuildA(const string& str) 14 { 15 std::cout<<"A:"<<str<<std::endl; 16 } 17 18 void CBuilder::BuildB(const string& str) 19 { 20 std::cout<<"B:"<<str<<std::endl; 21 }
Director.h
1 #pragma once 2 #include "IBuilder.h" 3 4 class CDirector 5 { 6 public: 7 CDirector(IBuilder* aBuilder); 8 ~CDirector(void); 9 public: 10 void Construct(); 11 private: 12 IBuilder* mBuilder; 13 };
Director.cpp
1 #include "Director.h" 2 3 4 CDirector::CDirector(IBuilder* aBuilder) 5 { 6 this->mBuilder = aBuilder; 7 } 8 9 10 CDirector::~CDirector(void) 11 { 12 delete mBuilder; 13 } 14 15 void CDirector::Construct() 16 { 17 this->mBuilder->BuildA("test"); 18 this->mBuilder->BuildB("hello"); 19 }
main.cpp
1 #include <iostream> 2 #include "Director.h" 3 #include "Builder.h" 4 5 int main() 6 { 7 CDirector* pDirector = new CDirector(new CBuilder()); 8 pDirector->Construct(); 9 return 0; 10 }
Tip:示例代码中没有使用Product。