建造者模式:建造过程相同,然后可以建造出不同的产品。简单工厂模式是同一个工厂生产不同的产品。侧重点有些区别。代码示例如下
/**
* @file builder.h
* @brief builder pattern
* @author timeshark
* @version 1.0
* @date 2018-08-07
*/
#ifndef BUILDER_H
#define BUILDER_H
#include <iostream>
using std::cout;
using std::endl;
class Builder {
public:
virtual void build_head() = 0;
virtual void build_body() = 0;
virtual void build_left_arm() = 0;
virtual void build_right_arm() = 0;
virtual void build_left_leg() = 0;
virtual void build_right_leg() = 0;
};
class ThinBuilder : public Builder {
public:
void build_head() { cout << "build thin head" << endl; }
void build_body() { cout << "build thin body" << endl; }
void build_left_arm() { cout << "build thin left arm" << endl; }
void build_right_arm() { cout << "build thin right arm" << endl; }
void build_left_leg() { cout << "build thin left leg" << endl; }
void build_right_leg() { cout << "build thin right leg" << endl; }
};
class FatBuilder : public Builder {
public:
void build_head() { cout << "build fat head" << endl; }
void build_body() { cout << "build fat body" << endl; }
void build_left_arm() { cout << "build fat left arm" << endl; }
void build_right_arm() { cout << "build fat right arm" << endl; }
void build_left_leg() { cout << "build fat left leg" << endl; }
void build_right_leg() { cout << "build fat right leg" << endl; }
};
class Director {
public:
Director(Builder *builder) : _builder(builder) {}
~Director() {
// 注意存在内存泄露问题
_builder = NULL;
}
void create() {
_builder->build_head();
_builder->build_body();
_builder->build_left_arm();
_builder->build_right_arm();
_builder->build_left_leg();
_builder->build_right_leg();
}
private:
Builder* _builder;
};
#endif
/**
* @file main.cpp
* @brief main
* @author timeshark
* @version 1.0
* @date 2018-08-07
*/
#include "builder.h"
int main() {
ThinBuilder thin;
FatBuilder fat;
Director director(&thin);
director.create();
Director director2(&fat);
director2.create();
return 0;
}
输出: