//
// 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;
}
Builder_A first_step
Builder_A second_step
Builder_A third_step
Director command succeed by command_A.
level 3 product succeed!
Builder_B first_step
Builder_B second_step
Director command succeed by command_B.
level 2 product succeed!
Program ended with exit code: 0
网友评论