Dog类
/*
* 构建者模式
*/
public class Dog {
private final String name;
private final String sex;
private final String age;
private Dog(Builder builder)
{
this.name = builder.name;
this.sex = builder.sex;
this.age = builder.age;
}
@Override
public String toString() {
return "name=" + name + ", sex=" + sex + ", age=" + age;
}
public static class Builder{
private String name;
private String sex;
private String age;
// public Builder()
// {
//
// }
public Builder name(String name)
{
this.name = name;
return this;
}
public Builder sex(String sex)
{
this.sex = sex;
return this;
}
public Builder age(String age)
{
this.age = age;
return this;
}
public Dog build()
{
return new Dog(this);
}
}
}
测试类
public class TestDogBuilder {
public static void main(String[] args)
{
Dog dog = new Dog.Builder().name("笨笨").age("20").sex("小公狗").build();
System.out.println(dog);
}
}
运行结果
name=笨笨, sex=小公狗, age=20