构造器参数有多个时要使用构建器builder
参数有多个,weight,height,log,nice多个参数,
其中weight和height参数是必须的,而log和nice参数是随机选择的,可以有其中一个,也可以两个都需要。
这是我们为了避免使用beans方法时由于线程不同步的因素,我们使用构建器。(builder)
在原来类的基础上创建内部类builder,builder中的属性和原来类Cat中的属性个数相同,然后:
1.把必须要的两个属性weight和height作为Builder的构造函数进行返回
2.其他的可以有的参数分别创建其构造的调用方法,
把这两种方式产生的属性都返回给Builder对象的属性
在创建一个Cat builder的方法,这个方法吧builder对象返回给new Cat(即使吧duilder对象的属性给了Cat对象)
这样就实现了对Cat类属性的随机选择添加(可以选择要添加的属性)
注意Cat对象 其在主方法中的调用方式
package builder;
public class Cat {
private final int height;
private final int weight;
private final int nice;
private final int log;
public static class Builder{
private int height;
private int weight;
private int nice = 0;
private int log = 0;
public Builder(int height,int weight)
{
this.height = height;
this.weight = weight;
}
public Builder nice(int nice)
{
this.nice = nice;
return this;
}
public Builder log(int log)
{
this.log = log;
return this;
}
public Cat builder()
{
return new Cat(this);
}
}
private Cat(Builder builder)
{
height = builder.height;
weight = builder.weight;
nice = builder.nice;
log = builder.log;
}
}
测试类
注意Cat对象 其在主方法中的调用方式
package builder;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Cat cat1 = new Cat.Builder(1, 1).nice(5).log(4).builder();
System.out.println("使用了builder方法构造了猫的各项信息");
}
}
当构造器参数较多,且部分参数可选时,为避免线程同步问题,可以使用构建器(Builder)模式。例如,Cat 类有 weight、height 必须参数及 log、nice 可选参数。构建器模式通过内部类 Builder 实现,将必填参数设为 Builder 构造函数,可选参数以单独方法设置,并最终由 Cat 的 builder 方法将 Builder 对象转换为 Cat 实例。这种设计允许灵活选择要设置的属性。
&spm=1001.2101.3001.5002&articleId=102884489&d=1&t=3&u=3dae456e7c004d2ba1c551aaf797e38a)
971

被折叠的 条评论
为什么被折叠?



