建造者模式
含义:
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。用具体的示例来说,就是装配一部手机,需要先放主板,再放屏幕,再放电池,最后组装外壳形成手机;而且每次发布新产品手机,更换更大的屏幕或者电池或者其他零部件,就又能卖出更好的价钱了。就是说,这些步骤都没变,变得只是每个部分的东西。
优点:
- 隔离了构建的步骤和具体的实现,为产品的具体实现提供了灵活度;
- 封装和抽象了每个步骤的实现,实现了依赖倒转原则;
- 封装了具体的步骤,减少了代码的冗余;
缺点:
- 要求构建产品的步骤(算法)是不能剧烈变化的,最好是不变的,这样就影响了灵活度;
对象说明:
- Director:指挥者,指挥建造产品的流程,或者负责安排已有模块的顺序,然后告诉Builder开始建造;
- Product产品类:通常是实现了模板方法模式,也就是有模板方法和基本方法;
- Builder抽象建造者:规范产品的组建,一般是由子类实现;
- ConcreteBuilder具体建造者:实现抽象类定义的所有方法,并且返回一个组建好的对象;
【笔者思考】
首先创建产品类(基类),每一个产品类下可以有多个产品(派生类),然后使用Builder类(基类)构建生产的规范,ConcreteBuilder(多个派生类)根据Builder类的规范分别进行每一个零部件的生产或组装,最后由Director类来指挥每一个零部件组装或生产前后的顺序。
示例:
//
// main.cpp
// builder_pattern
//
// Created by apple on 2019/3/12.
// Changed by apple on 2019/3/31
// Copyright © 2019年 apple. All rights reserved.
//
#include <iostream>
#include <string>
using std::cout;
using std::endl;
class IProduct//抽象产品类
{
public:
int num = 0;
virtual ~IProduct() {}
virtual void product() {this->num++;}
virtual void test() = 0;
};
class Product:public IProduct//实际产品
{
public:
void test(){cout<<"level "<<this->num<<" product succeed!"<<endl;}
};
class IBuilder//建造者接口定义了建造者的建造方法
{
public:
IProduct *product = NULL;
virtual void first_step() = 0;
virtual void second_step() = 0;
virtual void third_step() = 0;
virtual IProduct *GetProduct() = 0;
virtual ~IBuilder() {}
};
class Builder_A:public IBuilder//A建造者
{//建造者可以拥有很多用于构造产品的方法
public:
Builder_A() {this->product = new Product();}
void first_step(){product->product();cout<<"Builder_A first_step"<<endl;}
void second_step(){product->product();cout<<"Builder_A second_step"<<endl;}
void third_step(){product->product();cout<<"Builder_A third_step"<<endl;}
IProduct *GetProduct(){
return product;
}
~Builder_A() {delete product;}
};
class Builder_B:public IBuilder//B_建造者
{//建造者可以拥有很多用于构造产品的方法
public:
Builder_B() {this->product = new Product();}
void first_step(){product->product();cout<<"Builder_B first_step"<<endl;}
void second_step(){product->product();cout<<"Builder_B second_step"<<endl;}
void third_step(){}//注意third_step方法的区别
IProduct *GetProduct(){
return product;
}
~Builder_B() {delete product;}
};
class Director//导演类,使建造者执行命令
{
private:
IBuilder *builder;
public:
void setBuilder(IBuilder *builder){this->builder = builder;}
void command_A(){
builder->first_step();
builder->second_step();
builder->third_step();
this->builder->GetProduct();
cout<<"Director command succeed by command_A."<<endl;
}
void command_B(){
builder->first_step();
builder->second_step();
builder->third_step();
this->builder->GetProduct();
cout<<"Director command succeed by command_B."<<endl;
}
};
int main(int argc, const char * argv[]) {
Director director;//栈上导演
IBuilder *builder = NULL;//堆上建造者
builder = new Builder_A();
director.setBuilder(builder);
director.command_A();
builder->GetProduct()->test();
delete builder;
builder = NULL;
builder = new Builder_B();
director.setBuilder(builder);
director.command_B();
builder->GetProduct()->test();
delete builder;
builder = NULL;
return 0;
}