1. 创建和销毁对象
## *1.考虑用静态工厂方法代替构造器*
#### 优势
1.有名称
2.静态工厂方法不必每次调用它们的时候都创建一个新的对象
3.可以返回原返回类型的任何子类型的对象 ?
4.在创建参数化类型实例的时候,它们使代码变得更加简洁。
#### 区分“静态工厂方法”和“公有构造器”,理解各自的长处。
---
## *2.遇到多个构造器参数时要考虑用构建器*
```java
public class NutritionFacts{
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder{
private final int servingSize;
private final int servings;
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
public Builder(int servingSize,int servings){
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val){
calories = val;
return this;
}
public Builder fat(int val){
fat = val;
return this;
}
public Builder carbohydrate(int val){
carbohydrate = val;
return this;
}
public Builder sodium(int val){
sodium = val;
return this;
}
public NutritionFacts build(){
return new NutritionFacts(this);
}
}
privcate NutritionFacts(Builder builder){
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}
NutritionFacts cocaCola = new NutritionFacts.Builder(240,8).calories(100).sodium(35).carbohydrate(27).build();
```
总而言之:如果类的构造器或静态工厂具有多个参数,设计这种类的时候,Builder模式就是一个不错的选择。
3.用私有构造器或者枚举类型强化Singleton属性
单元素的枚举类型已经成为实现Singleton的最佳方法。
4.通过私有构造器强化不可实例化的能力
public class UtilityClass {
private UtilityClass(){
throw new AssertionError(); // 抛出AssertionError可以避免内部调用构造器
}
}
*5.避免创建不必要的对象*
String s = new String("aaa"); //不要这样
String s = "aaa"; //应该这样
```
//不要这么做
public class Person{
private final Data birthData;
public boolean isBabyBoomer(){
Calendar gmtCal=Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.set(1946, Calendar.JANUARY,1,0,0,0);
return ...
}
class Person{
private final Data birthDate;
private static final Date BOOM_START;
private static final Date BOOM_END;
// 使用静态代码块
static{
Calendar gmtCal=Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.set(1946, Calendar.JANUARY,1,0,0,0);
BOOM_START = gmtCal.getTime();
BOOM_END = ...
}
//改进后只需要创建一个实例
public boolean isBabyBoomer(){
return birthData.compareTo(BOOM_START) >= 0 && birthData.compareTo(BOOM_END) <0;
}
}
}
}
网友评论