123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154 |
- //构造器模式
- //构造器严格意义上来说不能算一个单独的设计模式,更多的是对各种组件的构造方式的封装
- #include<vector>
- #include<iostream>
- #include<string>
- //将一个类的构造函数进行封装,使得只能用特定的API才能构造对象(和后面的工厂有一些交叉的地方)
- class data //一个最简单的组件
- {
- private:
- int datas;
- public:
- data(int n):datas(n){}
- void print()
- {
- std::cout<<datas<<std::endl;
- }
- };
- //最简单的构造器(对对应对象的构造函数的封装)
- class basic_biulder
- {
- private:
- std::vector<data> 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<data> 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");
- }
|