建造者模式(Builder):主要用于创建一些复杂的对象,这些对象内部构建间的建造顺序通常是稳定的,但对象内部的构建通常面临着复杂的变化。其好处就是使得建造代码与表示代码分离,由于建造者隐藏了该产品是如何组装的,所以需要改变一个产品的内部表示,只需要再定义一个具体的建造者就可以了。建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方式时使用的模式。
#ifndef BUILDER_H #define BULDER_H #include<iostream> //#include<windows.graphics.printing.h> using namespace std; class Person { public: virtual void BuildHead()=0; virtual void BuildBody() = 0; virtual void BuildArmleft() = 0; virtual void BuildArmright() = 0; virtual void BuildLegleft() = 0; virtual void BuildLefrighy() = 0; }; class FatPerson :public Person { public: void BuildHead() { cout << "FatHead\n"; } void BuildBody() { cout << "FatBody\n"; } void BuildArmleft() { cout << "Fat Armleft\n"; } void BuildArmright() { cout << "Fat Armright\n"; } void BuildLegleft() { cout << "Fat Legleft\n"; } void BuildLefrighy() { cout << "Fat Legright\n"; } }; class ThinPerson :public Person { public: void BuildHead() { cout << "ThinHead\n"; } void BuildBody() { cout << "ThinBody\n"; } void BuildArmleft() { cout << "Thin Armleft\n"; } void BuildArmright() { cout << "Thin Armright\n"; } void BuildLegleft() { cout << "Thin Legleft\n"; } void BuildLefrighy() { cout << "Thin Legright\n"; } }; class PersonDirector { Person * per; public: PersonDirector(Person * m) :per(m){} void CreatPerson() { per->BuildArmleft(); per->BuildArmright(); per->BuildBody(); per->BuildHead(); per->BuildLefrighy(); per->BuildLegleft(); } }; #endif
#include"Bulder.h" int main() { Person * F = new FatPerson; PersonDirector PDf(F); PDf.CreatPerson(); Person * T = new ThinPerson; PersonDirector PDt(T); PDt.CreatPerson(); return 0; }
原文地址:http://blog.csdn.net/shiwazone/article/details/45664565