【Builder模式介绍】
不直接生产想要的对象,而是让客户端利用所有必要的参数调用构造器,得到一个builder对象。然后客户端在builder对象上调用类似setter的方法,来设置每个相关的可选参数。最后,客户端调用午餐的build方法来生成不可变的对象。这个builder就是它构建的类的静态成员类。
【示例】
public class BuilderPattern
{
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
public static class Builder
{
//必填参数
private final int servingSize;
private final int servings;
//可选参数,设置默认值
private int calories = 0;
private int fat = 0;
public Builder(int servingSize, int servings)
{
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val)
{
this.calories = val;
return this;
}
public Builder fat(int val)
{
this.fat = val;
return this;
}
public BuilderPattern build()
{
return new BuilderPattern(this);
}
}
private BuilderPattern(Builder builder)
{
this.servingSize = builder.servingSize;
this.servings = builder.servings;
this.calories = builder.calories;
this.fat = builder.fat;
}
public void myPrint()
{
System.out.println("servingSize = "+servingSize+", servings = "+servings+", calories = " +
+calories+", fat = "+fat);
}
public static void main(String[] args)
{
BuilderPattern bp = new Builder(240,8).calories(100).fat(35).build();
bp.myPrint();
}
}
网友评论