建造者模式:
将一个复杂对象的建造过程和它的表示分离开来,这样相同的建造过程可以创建不同的表示。
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
通俗一点就是如果流程是一样的,可以将这些流程抽象成一个类的一些接口,具体的创建过程可以在这个抽象类的子类中来实现。
C++中这个特性主要就是使用纯虚函数来实现。
UML图:
主要包括:
具体的C++代码如下:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <list>
#include <string>
using namespace std;
class Product
{
public:
void addPart(string str)
{
parts.push_back(str);
}
list<string>& getParts()
{
return parts;
}
private:
list<string> parts;
};
class Builder
{
public:
Builder()
{
product=new Product();
}
virtual void buildPart1()=0;
virtual void buildPart2()=0;
void getResult()
{
list<string>::iterator iter=product->getParts().begin();
for(;iter!=product->getParts().end();iter++)
{
std::cout<<*iter<<std::endl;
}
}
virtual ~Builder()
{
if(!product)
delete product;
}
protected:
Product *product;
};
class ConcreteBuilder1:public Builder
{
public:
void buildPart1()
{
product->addPart("part one");
}
void buildPart2()
{
product->addPart("part two");
}
};
class ConcreteBuilder2:public Builder
{
public:
void buildPart1()
{
product->addPart("part X");
}
void buildPart2()
{
product->addPart("part Y");
}
};
class Director
{
public:
Director()
{
}
Director(Builder * b):build(b)
{
}
void construct()
{
build->buildPart1();
build->buildPart2();
build->getResult();
}
private:
Builder *build;
};
int main()
{
std::cout<<"建造者模式测试"<<std::endl;
ConcreteBuilder1* cb1=new ConcreteBuilder1();
Director d1(cb1);
d1.construct();
ConcreteBuilder2 * cb2=new ConcreteBuilder2();
Director d2(cb2);
d2.construct();
return 0;
}
执行结果如下:
原文地址:http://blog.csdn.net/u012501459/article/details/46386655