构造器模式简介
对于大多数的类来说,直接使用构造函数便可得到想要的对像,对于复杂属性的类,可能多设几个构造函数,或构造函数多设几个参数也可能达到想要的结果。但对于复杂的对象有时还真是需要使用专门的构造器来获取适当对象。再说,对于C++开发来说,你搞个构造函数有七八个参数甚至更多,看你领导想不想批你!
对的,构造器模式是按需生成别的类对像的方法,但构造器本身肯定也是类了,要在这类里设置如何生成指定对像呢。
相关知识
1、如果获取某类型对象都考虑使用构造器了,那该类型本身的构造函数是否要私有呢?我想绝大多数情况都会吧。
2、、初始化成员变量并不一定必须能过构造函数传参,也可以用{}初始化。
class Dog
{
std::string name, weight, color;
//...
}
那么使用 Dog boMei{“bingo”, “15KG”, “withe”};也是可以的。
3、链式设置设计。像上面Dog 类,可能会有 setName(…), setWeight(…),setColor(…)等接口,那么如果每个函数返回自身引用能实现什么效果呢?
class Dog
{
std::string name, weight, color;
public:
Dog& setName(std::string nam){
name = nam; return *this;}
Dog& setWeight(std::string weigh){
weight = weigh; return *this;}
Dog& setColor(std::string clr) {
color = clr; return *this;}
//...
}
那么在连续设置属性时,可Dog dog; dog.setName(“bingo”).setWeight(“15KG”).setColor(“withe”); 。怎么样,方便很多吧?
4、假设有个构造器,class DogBuilder 是用来构造 Dog对象的,那么可以在构造器内部重载 Dog() ,这样就可以直接返回Dog 对象了
class DogBuilder
{
Dog dog;
public:
operator Dog() {
return std::move(dog);}
DogBuilder &setName(string nam) {
dog.setName(nam