//构造器模式 //构造器严格意义上来说不能算一个单独的设计模式,更多的是对各种组件的构造方式的封装 #include #include #include //将一个类的构造函数进行封装,使得只能用特定的API才能构造对象(和后面的工厂有一些交叉的地方) class data //一个最简单的组件 { private: int datas; public: data(int n):datas(n){} void print() { std::cout< elenment; public: void builder_data(int n) { elenment.emplace_back(data(n)); } void print() { for(auto i:elenment) { i.print(); } } }; //流式构造器 class builder { private: std::vector elenment; public: builder& builder_data(int n) { elenment.emplace_back(data(n)); return *this; } builder& print() { for(auto i:elenment) { i.print(); } return *this; } }; //组合构造器 //当然能不这么做尽量不要,结构乱七八糟的 class Personbuilder; class Personbuilderbase; class PersonbuilderAddress; class person //被构造的数据 { std::string address; std::string name; std::string post_code; std::string city; int age; person(){} friend Personbuilder; //只有设置为友元才能访问构造函数 friend PersonbuilderAddress; public: static Personbuilder create(); }; class Personbuilderbase { protected: person& p; explicit Personbuilderbase(person& data):p(data){} public: operator person() //类型转换运算符 { return std::move(p); } PersonbuilderAddress lives()const; }; class Personbuilder:public Personbuilderbase { person p; public: Personbuilder():Personbuilderbase(p){} }; Personbuilder person::create() { return Personbuilder(); } class PersonbuilderAddress:public Personbuilderbase { private: using self=PersonbuilderAddress; public: explicit PersonbuilderAddress(person& data):Personbuilderbase(data){} self& at(std::string address){ this->p.address=std::move(address); return *this; } //其余的赋值函数可以写在下面 }; PersonbuilderAddress Personbuilderbase::lives() const { return PersonbuilderAddress(p); } int main() { //简单构造器 basic_biulder test_1; test_1.builder_data(1); test_1.builder_data(2); test_1.builder_data(3); test_1.builder_data(4); test_1.print(); //流式构造器 builder test_2; test_2.builder_data(1).builder_data(2).builder_data(3).builder_data(4).print(); //能通过流式方法调用 //组合构造器 person data=person::create().lives().at("hello"); }