标签:
package cn.zno.common; public class Car { private String brand; private String type; private String color; public static class Builder { // 必填 private String brand; // 选填 private String type = "SUV"; private String color = "black"; public Builder(String brand) { this.brand = brand; } public Builder type(String type) { this.type = type; return this; } public Builder color(String color) { this.color = color; return this; } public Car build() { return new Car(this); } } /** * Builder 模式 * 不提供构造器 * */ private Car(Car.Builder builder) { this.brand = builder.brand; this.type = builder.type; this.color = builder.color; } @Override public String toString() { return "Car [brand=" + brand + ", type=" + type + ", color=" + color + "]"; } }
package lianxi; import org.junit.Test; import cn.zno.common.Car; import cn.zno.common.Car.Builder; public class CarTest { @Test public void f1() { Builder carBuilder = new Car.Builder("Benz"); Car car = carBuilder.build(); System.out.println(car); } @Test public void f2() { Builder carBuilder = new Car.Builder("Ford").type("Pickup").color("Red"); Car car = carBuilder.build(); System.out.println(car); } }
Car [brand=Benz, type=SUV, color=black] Car [brand=Ford, type=Pickup, color=Red]
标签:
原文地址:http://www.cnblogs.com/zno2/p/5470452.html