复习了一下静态工厂方法,发现,这个东西是真的好用。本质上他是干什么的呢?
其实就是我们在使用构造函数的时候,出现下面的情况:
date a=new date(1);
date a=new date(1,2);
date a=new date(1,2,3);
date a=new date(1,2,3,4);
date a=new date(1,2,3,4,5);
用了这些,如果代码是我们自己写的,我们还能看懂,但是如果是别人写的,我们看起来就一脸懵逼了。
那么应该怎么做呢。
public static Child newChild(int age, int weight) {
Child child = new Child();
child.weight = weight;
child.age = age;
return child;
}
public static Child newChildWithWeight(int weight) {
Child child = new Child();
child.weight = weight;
return child;
}
public static Child newChildWithAge(int age) {
Child child = new Child();
child.age = age;
return child;
}
我们这么写
然后可以调用
Child Durant=newChild(10, 50);
Child thompson=newChildWithWeight(50);
Child curry=newChildWithAge(10);
这样是不是就好了,
然后上述三个静态的方法,就是静态工厂方法的实例。
静态工厂方法的好处,当然不止这些还有很多,这里就介绍一下实例,想知道更多就百度其他的吧。
总体来说,我觉得『考虑使用静态工厂方法代替构造器』这点,除了有名字、可以用子类等这些语法层面上的优势之外,更多的是在工程学上的意义,我觉得它实质上的最主要作用是:能够增大类的提供者对自己所提供的类的控制力。使我们更少受构造函数的限制。