图1 建造者模式【点击查看大图】
基本的知识点已在思维导图中,下面是demo
1,Builder
为创建一个产品对象的各个部件指定抽象接口
public interface PersonBuilder { void buildHead(); void buildBody(); void buildFoot(); Person buildPerson(); }
2,ConcreteBuilder
实现Builder的接口以构造和装配该产品的各个部件,定义并明确它所创建的表示,并提供一个检索产品的接口
class ManBuilder implements PersonBuilder { Person person; public ManBuilder() { person = new Man(); } public void buildHead() { person.setHead("建造男人的头"); } public void buildBody() { person.setBody("建造男人的身体"); } public void buildFoot() { person.setFoot("建造男人的脚"); } public Person buildPerson() { return person; } } 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; } }
3,Director
构造一个使用Builder接口的对象,指导构建过程
public class PersonDirector { public Person constructPerson(PersonBuilder pb) { pb.buildHead(); pb.buildBody(); pb.buildFoot(); return pb.buildPerson(); } }
4,Product
表示被构造的复杂对象。ConcreteBuilder创建该产品的内部表示并定义它的装配过程,包含定义组成部件的类,包括将这些部件装配成最终产品的接口
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; } } class Man extends Person { public Man(){ System.out.println("开始建造男人"); } } class Woman extends Person { public Woman(){ System.out.println("开始建造女人"); } }
5,Test验证代码
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()); } }