建造者模式的简易实现(在同一个类中用静态内部类实现)

1. 实体情况:

@ToString
public class Person {
private Long id;
private String personName;
private int age;

public Person(Long id, String personName, int age) {
this.id = id;
this.personName = personName;
this.age = age;
}

public static Person.PersonBuilder builder() {
return new Person.PersonBuilder();
}

public static class PersonBuilder {
private Long id;
private String personName;
private int age;

public Person.PersonBuilder id(Long id) {
this.id = id;
return this;
}

public Person.PersonBuilder personName(String personName) {
this.personName = personName;
return this;
}

public Person.PersonBuilder age(int age) {
this.age = age;
return this;
}

public Person build() {
return new Person(this.id, this.personName, this.age);
}
}
}

2. 测试代码:

    public static void main(String[] args) {
// Person person = new Person.PersonBuilder()
// .id(1L)
// .personName("zhangsan")
// .age(20)
// .build();

Person person = Person.builder()
.id(1L)
.personName("zhangsan")
.age(20)
.build();

System.out.println(person);
}

猜你喜欢

转载自www.cnblogs.com/modestlin/p/12367928.html