设计模式——Builder模式
作者:互联网
package com.example.pro.test;
import lombok.Data;
/**
* @Author: liutengyuan
* @Date: 2019/8/23 13:06
*
*/
@Data
public class Person {
private String name;
private int age;
private String sex;
private String profession;
private String interest;
public Person(PersonBuilder builder) {
this.name = builder.name;
this.age = builder.age;
this.sex = builder.sex;
this.profession = builder.profession;
this.interest = builder.interest;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", profession='" + profession + '\'' +
", interest='" + interest + '\'' +
'}';
}
static class PersonBuilder{
private String name;
private int age;
private String sex;
private String profession;
private String interest;
public PersonBuilder(String name, int age) {
this.name = name;
this.age = age;
}
public PersonBuilder sex (String sex){
this.sex = sex;
return this;
}
public PersonBuilder profession (String profession){
this.profession = profession;
return this;
}
public PersonBuilder interest (String interest){
this.interest = interest;
return this;
}
public Person build(){
return new Person(this);
}
}
}
测试
public class TestPersonBuilder {
public static void main(String[] args) {
Person person = new Person.PersonBuilder("花花", 20)
.sex("男")
.interest("钢琴")
.profession("作家")
.build();
System.out.println(person.toString());
}
}
参考文章:
https://www.jianshu.com/p/afe090b2e19c
标签:String,Builder,profession,模式,sex,private,interest,设计模式,public 来源: https://blog.csdn.net/liutengyuan/article/details/100036237