item 1. 尽量使用静态方法提供类实例对象,而不是直接使用构造方法。
优点:
- 方法有名字,可以知道具体是怎样的实例
- 不需要每次创建新对象
- 方法可以返回 返回值类型的 子类对象
- 方法返回对象的类不需要存在(返回接口类型)
缺点:
- 只提供静态方法,而构造函数又不是public或protected的类无法被继承。
- 静态方法不容易被找到。
item2 当构造函数有多个参数时,考虑builder模式
/**
* @author: lwn
* @version: 1.0
* @Description: builder模式,一种特殊的构造函数,其权限私有,参数为builder类型,builder类为该类的静态内部类。
* 好处是:生成对象时,可以链式调用set方法设置属性,适合需要设置多个属性的对象生成。
* @date: 2021/10/21 9:24
*/
public class BuilderPattern {
public static void main(String[] args) {
People p = new People.Builder().setAge(10).setName("lwn").build();
System.out.printf("p.age = %d, p.name = %s\n", p.getAge(),p.getName());
}
}
class People {
private int age;
private String name;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public static class Builder {
private int age;
private String name;
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public People build() {
return new People(this);
}
}
private People(Builder b) {
age = b.age;
name = b.name;
}
}