标签:c++ 设计模式
建造者模式,将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。#include "stdafx.h" #include <iostream> #include <string> using namespace std; class Product { private: std::string _partA; std::string _partB; std::string _partC; public: void SetPartA(const string& partA) { cout << "Product:A" << endl; _partA = partA; } void SetPartB(const string& partB) { cout << "Product:B" << endl; _partB = partB; } void SetPartC(const string& partC) { cout << "Product:C" << endl; _partC = partC; } }; class Builder { public: virtual void BuildPartA() = 0; virtual void BuildPartB() = 0; virtual void BuildPartC() = 0; virtual Product* GetProduct() = 0; Builder(){} virtual ~Builder(){} }; class ConcreteBuilder :public Builder { private: Product* _pProduct; public: ConcreteBuilder() :Builder() { _pProduct = new Product(); } ~ConcreteBuilder() { delete(_pProduct); _pProduct = NULL; } virtual void BuildPartA() { cout << "ConcreteBuilder:A" << endl; _pProduct->SetPartA("A"); } virtual void BuildPartB() { cout << "ConcreteBuilder:B" << endl; _pProduct->SetPartB("B"); } virtual void BuildPartC() { cout << "ConcreteBuilder:C" << endl; _pProduct->SetPartC("C"); } virtual Product* GetProduct() { return this->_pProduct; } }; class Director { private: Builder *_pBuilder; public: ~Director() { } Director(Builder* builder) { _pBuilder = builder; } void Construct() { _pBuilder->BuildPartA(); _pBuilder->BuildPartB(); _pBuilder->BuildPartC(); } };
// BuilderPattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Builder.h" int _tmain(int argc, _TCHAR* argv[]) { Director *pDirector = new Director(new ConcreteBuilder()); pDirector->Construct(); getchar(); return 0; }
标签:c++ 设计模式
原文地址:http://blog.csdn.net/wwwdongzi/article/details/26683537