建造者模式,将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
Builder是为创建一个Product对象的各个部件指定的抽象接口。
ConcreteBuilder是具体建造者,实现Builder接口,构造和装配各个部件。
Product是产品角色
Director是指挥者,是构建一个使用Builder接口的对象
建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时适用的模式。
#include <iostream> using namespace std; class People //抽象类 人类 { public: virtual void CreateHead() = 0; //纯虚函数 创建头 virtual void CreateHand() = 0; //纯虚函数 创建手 virtual void CreateBody() = 0; //纯虚函数 创建身体 virtual void CreateFoot() = 0; //纯虚函数 创建脚 }; class Fatty : public People //胖子类 继承于人类 { public: void CreateHead() //实现纯虚函数 创建头 { cout<<"胖子 头"<<endl; } void CreateHand() //实现纯虚函数 创建手 { cout<<"胖子 手"<<endl; } void CreateBody() //实现纯虚函数 创建身体 { cout<<"胖子 身体"<<endl; } void CreateFoot() //实现纯虚函数 创建脚 { cout<<"胖子 脚"<<endl; } }; class ThinPeople : public People //瘦子类 继承于人类 { public: void CreateHead() //实现纯虚函数 创建头 { cout<<"瘦子 头"<<endl; } void CreateHand() //实现纯虚函数 创建手 { cout<<"瘦子 手"<<endl; } void CreateBody() //实现纯虚函数 创建身体 { cout<<"瘦子 身体"<<endl; } void CreateFoot() //实现纯虚函数 创建脚 { cout<<"瘦子 脚"<<endl; } }; class Direct //指挥者类 { People* peo; //抽象类型指针 public: Direct(People* temp):peo(temp){}; //构造函数 传入胖子类指针或者瘦子类指针 并转化为人类指针 void create() //创建胖子或瘦子 { peo->CreateHead(); peo->CreateHand(); peo->CreateBody(); peo->CreateFoot(); } }; int main() { Fatty* fat = new Fatty; //胖子类实例 Direct* dir = new Direct(fat); //指挥者类实例 dir->create(); //开始创建 cout<<endl; ThinPeople* thin = new ThinPeople; //瘦子类实例 Direct* dir0 = new Direct(thin); //指挥者类实例 dir0->create(); //开始创建 return 0; }
