学习新的东西我们要有两点清楚的认识
1.为什么要学习它?
2.它在实际中都会帮我们起到一个什么样的作用?
// 在实际的操作中我们经常会创建bean对象如下:
public class User {
private String name;
private Integer age;
private String address;
private String city;
get();set();
...
}
//有时候我们为了方便传值就不会一个一个set,这个时候我们可以使用有参构造如下:
public class User {
private String name;
private Integer age;
private String address;
private String city;
public User( String name, Integer age, String city, String address){
this.name = name;
if( null == age ){
this.age = 0;
}else{
this.age = age ;
}
this.city= city;
this.address = address;
}
public User( String city, String address){
this.city= city;
this.address = address;
}
get();set();
...
}
//出现上面的情况时(参数过多),涉及到的有参构造就会越多如
new User("张三",11,null,null);
new User("张三",null,null,null);//有些时候我们也并不想给其他的赋值,我们却还要写多余的代码..
//我们就该考虑要不要使用建造者模式了,首先我们先来看一下建造者模式:
public class User {
private final String name;//定义final
private final Integer age;
private final String city;
private final String address;
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public String getCity() {
return city;
}
public String getAddress() {
return address;
}
public static class Builder{
private String name;
private Integer age = 0 ; //定义初始值
private String city;
private String address;
public Builder (String name){
this.name = name ;
}
public Builder age(Integer ageValue){
age = ageValue;
return this;
}
public Builder city(String cityValue){
city = cityValue;
return this;
}
public Builder address(String addressValue){
address = addressValue;
return this;
}
public User build() { // 定义空参构造,调用User有参构造
return new User(this);
}
}
private User(User.Builder b) {
name = b.name;
age = b.age;
city = b.city;
address = b.address;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
", address='" + address + '\'' +
'}';
}
public static void main(String[] args) {
//1.可以随意的进行赋值 并且很明了
//2.可以随意的定义初始值并且很明了
User user = new Builder("张三").age(11).city("北京").address("海淀").build();
System.out.println(user);
}
}
1.为什么要学习它?
有时候在开发过程中,赋值不定的时候这种方式会给我们带来便利;
2.它在实际中都会帮我们起到一个什么样的作用?
1.赋值简单明了 2.参数任意
由于学的比较浅显,会在工作之中进行总结更新~