建造者模式的优缺点
优点:
1、降低代码耦合度。在建造者模式中,客户端不需要知道产品内部是如何实现的,我们只需得到产品的对象。并且使用导演者和建造者分离组装过程和组件具体构造过程,具有灵活的扩展性。
2、优秀的扩展性。具体建造者相互独立,方便扩展,符合开闭原则。
缺点:
一定的使用范围限制。建造者模式的产品的组件基本相同,如果产品的差异性较大,建造者模式就不适用了。
比较
跟工厂方法模式对比:建造者模式和工厂模式同样是创建一个产品,工厂模式就是一个方法,而建造者模式有多个方法,并且建造者模式是有顺序的执行方法。就是说建造者模式强调的是顺序,而工厂模式没有顺序一说。
建造者模式和模板方法模式非常的相似,只是比模板方法模式多了一个类,指挥类, 该类就是模板中基类的固定算法的功能相同,它是一个创建对象的固定算法。 他两的使用范围区分就看构建的算法是否需要另外创建一个类。
#include <iostream>
using namespace std;
// Builder(建造工厂)
class Builder
{
public:
virtual void build_head() = 0; // head
virtual void build_body() = 0; // body
virtual void build_arms() = 0; // arm
virtual void build_legs() = 0; // leg
virtual void build_private_part() = 0; // private part
};
// man
class ManBuilder : public Builder
{
public:
void build_head()
{
cout << "build man head" << endl;
}
void build_body()
{
cout << "build man body" << endl;
}
void build_arms()
{
cout << "build man arm" << endl;
}
void build_legs()
{
cout << "build man leg" << endl;
}
void build_private_part()
{
cout << "build xiao dd" << endl;
}
};
// woman
class WomanBuilder : public Builder
{
public:
void build_head()
{
cout << "build woman head" << endl;
}
void build_body()
{
cout << "build woman body" << endl;
}
void build_arms()
{
cout << "build woman arm" << endl;
}
void build_legs()
{
cout << "build woman leg" << endl;
}
void build_private_part()
{
cout << "build xiao mm" << endl;
}
};
// NuWa(指挥官)
class NuWa
{
public:
NuWa(Builder* b)
{
builder = b;
}
void Create()
{
cout << "开始造人..." << endl;
builder->build_head();
builder->build_body();
builder->build_arms();
builder->build_legs();
builder->build_private_part();
}
private:
Builder* builder;
};
void test_01()
{
// build man
Builder* builder = new ManBuilder;
NuWa* nw = new NuWa(builder);
nw->Create();
delete builder;
delete nw;
cout << "*****************" << endl;
// build woman
builder = new WomanBuilder;
nw = new NuWa(builder);
nw->Create();
delete builder;
delete nw;
}
int main(int argc, char* argv[])
{
test_01();
system("pause");
return 0;
}