/** * 为创建一个产品对象的各个部件指定接口 * @author swt */ public interface PersonBuilder { /** * 创建头 */ void buildHead(); /** * 创建身体 */ void buildBody(); /** * 创建身体 */ void buildFoot(); /** * 创建产品 * @return 产品 */ Person buildPerson(); }
public class ManBuilder implements PersonBuilder { private Person person; public ManBuilder() { person = new ManPerson(); } @Override public void buildHead() { System.out.println("创建男人的头"); } @Override public void buildBody() { System.out.println("创建男人的身体"); } @Override public void buildFoot() { System.out.println("创建男人的脚"); } @Override public Person buildPerson() { return person; } }
public class WomanBuilder implements PersonBuilder { private Person person; public WomanBuilder() { person = new WomanPerson(); } @Override public void buildHead() { System.out.println("创建女人的头"); } @Override public void buildBody() { System.out.println("创建女人的身体"); } @Override public void buildFoot() { System.out.println("创建女人的脚"); } @Override public Person buildPerson() { return person; } }
/** * 要创建的产品 * @author swt */ 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; } }
/** * 要创建的产品1 * @author swt */ public class ManPerson extends Person{ public ManPerson() { System.out.println("开始创建产品 ManPerson"); } }
/** * 要创建的产品2 * @author swt */ public class WomanPerson extends Person{ public WomanPerson() { System.out.println("开始创建产品 WomanPerson"); } }
/** * 构造一个使用Builder接口的对象,指导构建过程。 * @author swt */ public class PersonDirector { public Person constructPerson(PersonBuilder personBuilder) { personBuilder.buildHead(); personBuilder.buildBody(); personBuilder.buildFoot(); return personBuilder.buildPerson(); } }
public class Main { public static void main(String[] args) { PersonDirector personDirector = new PersonDirector(); Person person = personDirector.constructPerson(new ManBuilder()); person = personDirector.constructPerson(new WomanBuilder()); } }
输出
开始创建产品 ManPerson 创建男人的头 创建男人的身体 创建男人的脚 开始创建产品 WomanPerson 创建女人的头 创建女人的身体 创建女人的脚