Builder 模式的适用场景
1、 创建的对象参数比较多,较复杂。
2、构建过程中,步骤相同,但因引入的参数不同可导致对象不同。
实现过程:
public class PhoneState { private int id; private String ram; private String rom; private float system_version; PhoneState(Builder builder){ this.id = builder.id; this.ram = builder.ram; this.rom = builder.rom; this.system_version = builder.system_version; } public static class Builder{ private int id; private String ram; private String rom; private float system_version; public Builder(int id){ this.id = id; } public Builder ram(String ram){ this.ram = ram; return this; } public Builder rom(String rom){ this.rom = rom; return this; } public Builder system_version(float system_version){ this.system_version = system_version; return this; } public PhoneState build(){ return new PhoneState(this); } } @Override public String toString() { return "PhoneState [id=" + id + ", ram=" + ram + ", rom=" + rom + ", system_version=" + system_version +"]"; } }
调用:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PhoneState phoneState = new PhoneState.Builder(1) .ram("8GB") .rom("128GB") .system_version(7.1f) .build(); Log.e("ACETEST", "phoneState: " + phoneState.toString() ); } }
打印:
PhoneState [id=1, ram=8GB, rom=128GB, system_version=7.1]