介绍:
构造者模式,又称之为建造者模式,建造者模式,单例模式以及工厂模式都属于创建型模式
应用场景
当一个bean类重载了多个构造方法时,并且参数随机使用时,考虑使用构造者模式,
Demo
package com.yunsuibi;
public class User {
private final String firstName; // required
private final String lastName; // required
private final int age; // optional
private final String phone; // optional
private final String address; // optional
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
@Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", phone=" + phone
+ ", address=" + address + "]";
}
public static class UserBuilder {
private final String firstName;
private final String lastName;
private int age;
private String phone;
private String address;
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
public User build() {
return new User(this);
}
}
}
运行
public static void main(String[] args) {
User build = new User.UserBuilder("Jhon", "Doe").address("北京").build();
System.out.println(build);
User build2 = new User.UserBuilder("李四", "哈哈").address("12").build();
System.out.println(build2);
}
个人博客 百度搜索:云随笔
可以关注下博主的公众号,实时推送解决方案!