Builder模式
Builder模式要解决的问题是把对象的构建和对象的表示分开来。当对象复杂的时候我,我们可以一步步来构建对象,在每一步的构建过程中,可以引入参数,通过不同的参数,即使经过相同的步骤最后可以得到不同的对象。
通过一个实例来说明,Product是我们要构建的对象,在Builder类中构建,通过BuildPartA、BuildPartB、BuildPartC三步来构建对象,一个ConcreteBuilder类来具体实现Builder类,通过Director类来调用Builder类指导构建过程。
下图是Builder模式的类结构图。
//Product.h
#ifndef _PRODUCT_H
#define _PRODUCT_H
class Product
{
public:
Product();
~Product();
void ProductPart();
protected:
private:
};
class ProductPart
{
public:
ProductPart();
~ProductPart();
ProductPart* BuildPart();
protected:
private:
};
#endif
//Product.cpp
#include"Product.h"
#include<iostream>
Product::Product()
{
std::cout << "Product Ctor" << std::endl;
}
Product::~Product()
{
std::cout << "Product Dtor" << std::endl;
}
void Product::ProductPart()
{
}
ProductPart::ProductPart()
{
std::cout << "ProductPart Cotr" << std::endl;
}
ProductPart::~ProductPart()
{
std::cout << "ProductPart Dtor" << std::endl;
}
ProductPart* ProductPart::BuildPart()
{
return NULL;
}
//Builder.h
//Builder.cpp
#include"Builder.h"
#include"Product.h"
#include<iostream>
using namespace std;
Builder::Builder()
{
}
Builder::~Builder()
{
}
ConcreteBuilder::ConcreteBuilder()
{
}
ConcreteBuilder::~ConcreteBuilder()
{
}
void ConcreteBuilder::BuildPartA(const string& buildPara)
{
cout << "Step1: Build PartA..." << buildPara << endl;
}
void ConcreteBuilder::BuildPartB(const string& buildPara)
{
cout << "Step2: Build PartB..." << buildPara << endl;
}
void ConcreteBuilder::BuildPartC(const string& buildPara)
{
cout << "Step3: Build PartC..." << buildPara << endl;
}
Product* ConcreteBuilder::GetProduct()
{
BuildPartA("pre-define");
BuildPartB("pre-define");
BuildPartC("pre-define");
return new Product();
}
//Director.h
//Director.h
#ifndef _DIRECTOR_H_
#define _DIRECTOR_H_
class Builder;
class Director
{
public:
Director(Builder* bld);
~Director();
void Construct();
protected:
private:
Builder* _bld;
};
#endif
//Director.cpp
//Director.cpp
#include"Director.h"
#include"Builder.h"
Director::Director(Builder* bld)
{
_bld = bld;
}
Director::~Director()
{
}
void Director::Construct()
{
_bld->BuildPartA("user-define");
_bld->BuildPartB("user-define");
_bld->BuildPartC("user-define");
}
//main.cpp
//main.cpp
#include"Builder.h"
#include"Product.h"
#include"Director.h"
#include<iostream>
int main(int agrc, char* agrv[])
{
Director* d = new Director(new ConcreteBuilder());
d->Construct();
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-06 07:04:32