1.构建者模式
灵活地构建多个成员变量的复杂对象。
2.示例
public class Human
{
private String head;
private String body;
private String foot;
public Human(Builder builder)
{
this.head = builder.head;
this.body = builder.body;
this.foot = builder.foot;
}
public String getHead()
{
return head;
}
public String getBody()
{
return body;
}
public String getFoot()
{
return foot;
}
@Override
public String toString()
{
return "Human:"+this.head+"-"+this.body+"-"+this.foot;
}
public static class Builder{
private String head;
private String body;
private String foot;
public Builder setHead(String head)
{
this.head = head;
return this;
}
public Builder setBody(String body)
{
this.body = body;
return this;
}
public Builder setFoot(String foot)
{
this.foot = foot;
return this;
}
public Human build()
{
return new Human(this);
}
}
}
Human human = new Human.Builder().setBody("身体").setHead("头").setFoot("脚").build();
System.out.println(human);
直接使用具体Builder和具体的产品直接进行构建组建自己。而且在构建完部件以后,直接返回该Builder对象,方便链式调用,也达到了一句话创建复杂对象的过程。