标签:os io ar 代码 amp sp on new c
建造者模式和工厂模式稍微有点像,但是建造者模式更适用与遵循一定的规则进行创建。例如,和美女乱搞,都要经过脱鞋,脱裤子,脱上衣这些流程,但是每个人脱的方式不一样,脱得顺序也不一样,适用于建造者模式。
代码如下:
#include <iostream> using namespace std; class Builder { public: Builder() {} virtual ~Builder() {} private: Builder(const Builder& build); Builder& operator = (const Builder& build); public: virtual void Create() = 0; virtual void OffShone() = 0; virtual void OffJacket() = 0; virtual void OffPants() = 0; }; class BuilderA : public Builder { public: BuilderA() {} ~BuilderA() {} private: BuilderA(const BuilderA& build); BuilderA& operator = (const BuilderA& build); public: void OffShone() { cout<< "A offshone" << endl; } void OffJacket() { cout << "A offjacket" << endl; } void OffPants() { cout<< "A offpants" << endl; } void Create() { OffPants(); OffShone(); OffJacket(); } }; class BuilderB : public Builder { public: BuilderB() {} ~BuilderB() {} private: BuilderB(const BuilderB& build); BuilderB& operator = (const BuilderB& build); public: void OffShone() { cout<< "B offshone" << endl; } void OffJacket() { cout << "B offjacket" << endl; } void OffPants() { cout<< "B offpants" << endl; } void Create() { OffShone(); OffPants(); OffJacket(); } }; class Director { public: Director(Builder* build) { build_ = build; } ~Director() { if (build_) { delete build_; build_ = NULL; } } private: Director(const Director& d); Director& operator = (const Director& d); public: void Create() { build_->Create(); } private: Builder* build_; };
#include "main.h" int main(int argc, char* argv[]) { Builder* build_a = new BuilderA(); Builder* build_b = new BuilderB(); Director* derector_a = new Director(build_a); Director* derector_b = new Director(build_b); derector_a->Create(); derector_b->Create(); }
标签:os io ar 代码 amp sp on new c
原文地址:http://my.oschina.net/hejiula/blog/307172