大家好,又见面了,我是全栈君。
public interface PersonBuilder {
void buildHead();
void buildBody();
void buildFoot();
Person buildPerson();
}
public class ManBuilder implements PersonBuilder {
Person person;
public ManBuilder() {
person = new Man();
}
public void buildbody() {
person.setBody("建造男人的身体");
}
public void buildFoot() {
person.setFoot("建造男人的脚");
}
public void buildHead() {
person.setHead("建造男人的头");
}
public Person buildPerson() {
return person;
}
}
public class WomanBuilder implements PersonBuilder {
Person person;
public WomanBuilder() {
person = new Woman();
}
public void buildbody() {
person.setBody(“建造女人的身体");
}
public void buildFoot() {
person.setFoot(“建造女人的脚");
}
public void buildHead() {
person.setHead(“建造女人的头");
}
public Person buildPerson() {
return person;
}
}
public class PersonDirector {
public Person constructPerson(PersonBuilder pb) {
pb.buildHead();
pb.buildBody();
pb.buildFoot();
return pb.buildPerson();
}
}
public class Person { private String head; private String body; 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 getFoot() { return foot; } public void setFoot(String foot) { this.foot = foot; }}public class Man extends Person { public Man(){ System.out.println(“开始建造男人"); }}public class Woman extends Person { public Woman(){ System.out.println(“开始建造女人"); }}
public class Test{ public static void main(String[] args) { PersonDirector pd = new PersonDirector(); Person womanPerson = pd.constructPerson(new ManBuilder()); Person manPerson = pd.constructPerson(new WomanBuilder()); }}
public class Man { private String head; private String body; 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 getFoot() { return foot; } public void setFoot(String foot) { this.foot = foot; }}
public class ManBuilder{ Man man; public ManBuilder() { man = new Man(); } public void buildbody() { man.setBody("建造男人的身体"); } public void buildFoot() { man.setFoot("建造男人的脚"); } public void buildHead() { man.setHead("建造男人的头"); } public Man builderMan() { buildHead(); buildBody(); buildFoot(); return man; }}
public class Test{ public static void main(String[] args) { ManBuilder builder = new ManBuilder(); Man man = builder.builderMan(); }}
更多设计模式:
23种设计模式系列
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/121326.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...