标签:参数 uil using 很多 需要 private 必须 客户端 iss
一.生成器模式要解决的问题
生成器模式主要解决工厂方法模式和抽象工厂模式在所创建的对象包含大量的属性时所面临的问题:
二.生成器模式的要点
三.附java代码如下
class Phone{
private String cpu;
private String memory;
private boolean isRedColor;
private boolean isFullScreen;
private Phone(PhoneBuilder phoneBuilder){
//必须的参数
this.cpu=phoneBuilder.cpu;
this.memory=phoneBuilder.memory;
//可选的参数
this.isRedColor=phoneBuilder.isRedColor;
this.isFullScreen=phoneBuilder.isFullScreen;
}
private static class PhoneBuilder{
// 必须的参数
private String cpu;
private String memory;
// 可选的参数
private boolean isRedColor;
private boolean isFullScreen;
public PhoneBuilder(String cpu,String memory){
this.cpu=cpu;
this.memory=memory;
}
public PhoneBuilder setColor(boolean redColor){
this.isRedColor=redColor;
return this;
}
public PhoneBuilder setFullScreen(boolean fullScreen){
this.isFullScreen=fullScreen;
return this;
}
public Phone builder(){
return new Phone(this);
}
}
}
与客户端程序交互代码如下:
public class TestBuilderPattern { public static void main(String[] args) { //Using builder to get the object in a single line of code and //without any inconsistent state or arguments management issues Phone phone = new Phone.PhoneBuilder( "1.5 GHz", "2 GB").setBluetoothEnabled(true) .setGraphicsCardEnabled(true).build(); } }
标签:参数 uil using 很多 需要 private 必须 客户端 iss
原文地址:https://www.cnblogs.com/quxiangxiangtiange/p/10211970.html