建造者
-
建造者设计模式是什么?有啥么用?
- 链式调用
-
建造者的常用写法
-
建造者的神器?
- lombok
User.java
package course.patterns.builder; public class User { private String name; private Integer age; private String info; private String password; private String balance; private User(Builder builder) { this.name = builder.name; this.age = builder.age; this.info = builder.info; this.password = builder.password; this.balance = builder.balance; } public static class Builder { private String name; private Integer age; private String info; private String password; private String balance; public static Builder of() { return new Builder(); } public Builder name(String name) { this.name = name; return this; } public Builder age(Integer age) { this.age = age; return this; } public Builder info(String info) { this.info = info; return this; } public Builder password(String password) { this.password = password; return this; } public Builder balance(String balance) { this.balance = balance; return this; } public User build() { return new User(this); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", info='" + info + '\'' + ", password='" + password + '\'' + ", balance='" + balance + '\'' + '}'; } }
UserApp1
package course.patterns.builder; public class UserApp1 { // public static void main(String[] args) { // User user = new User(); // user.setName("xxx"); // user.setAge(23); // user.setPassword("122333"); // // fooUser(user); // } // public static void main(String[] args) { User user = User.Builder.of() .name("") .age(23) .balance("123") .info("") .build(); fooUser(user); fooUser(User.Builder.of() .name("") .age(23) .balance("123") .info("") .build()); } private static void fooUser(User user) { } }
User2.java
package course.patterns.builder; import lombok.Builder; import lombok.Data; @Builder @Data public class User2 { private String name; private Integer age; private String info; private String password; private String balance; }
UserApp2.java
package course.patterns.builder; public class User2App { public static void main(String[] args) { User2 fly = User2.builder().name("Fly") .age(23) .balance("123") .info("") .build(); } }