0、建造者模式的实现方式
建造者模式的实现方式有2种,一种是原型还有一种是本文介绍的方法链的形式。
原型可以查看文章:https://blog.csdn.net/u010102390/article/details/80179754
1、我们还是以一个human作为例子,首先建立一个human类
为了节省篇幅,get和set就不放出来了,注意要有无参和全参2个构造方法
public class Human {
private String head;
private String body;
private String hand;
private String foot;
/** setter and getter **/
public Human() {
}
public Human(String head, String body, String hand, String foot) {
this.head = head;
this.body = body;
this.hand = hand;
this.foot = foot;
}
@Override
public String toString() {
return "Human{" +
"head='" + head + '\'' +
", body='" + body + '\'' +
", hand='" + hand + '\'' +
", foot='" + foot + '\'' +
'}';
}
}
2、创建一个builder内部类,同时在外部类创建一个builder方法,注意2个都要加上static
public static Human.HumanBuilder builder() {
return new Human.HumanBuilder();
}
public static class HumanBuilder {
private String head;
private String body;
private String hand;
private String foot;
public Human.HumanBuilder head(String head) {
this.head = head;
return this;
}
public Human.HumanBuilder body(String body) {
this.body = body;
return this;
}
public Human.HumanBuilder hand(String hand) {
this.hand = hand;
return this;
}
public Human.HumanBuilder foot(String foot) {
this.foot = foot;
return this;
}
public Human build() {
return new Human(this.head, this.body, this.hand, this.foot);
}
}
3、写一个测试方法来测试一下
@Test
public void testAllay() {
Human human = Human.builder().head("头").body("身体").hand("手").foot("脚").build();
System.out.println("build success: " + human);
}
至此,方法链形式的构造者模式就完成了
4、这里放出完整的human类
public class Human {
private String head;
private String body;
private String hand;
private String foot;
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getHand() {
return hand;
}
public void setHand(String hand) {
this.hand = hand;
}
public String getFoot() {
return foot;
}
public void setFoot(String foot) {
this.foot = foot;
}
public Human() {
}
public Human(String head, String body, String hand, String foot) {
this.head = head;
this.body = body;
this.hand = hand;
this.foot = foot;
}
public static Human.HumanBuilder builder() {
return new Human.HumanBuilder();
}
@Override
public String toString() {
return "Human{" +
"head='" + head + '\'' +
", body='" + body + '\'' +
", hand='" + hand + '\'' +
", foot='" + foot + '\'' +
'}';
}
public static class HumanBuilder {
private String head;
private String body;
private String hand;
private String foot;
public Human.HumanBuilder head(String head) {
this.head = head;
return this;
}
public Human.HumanBuilder body(String body) {
this.body = body;
return this;
}
public Human.HumanBuilder hand(String hand) {
this.hand = hand;
return this;
}
public Human.HumanBuilder foot(String foot) {
this.foot = foot;
return this;
}
public Human build() {
return new Human(this.head, this.body, this.hand, this.foot);
}
}
}