标签:
其核心思想是将一个“复杂对象的构建算法”与它的“部件及组装方式”分离,使得构件算法和组装方式可以独立应对变化;复用同样的构建算法可以创建不同的表示,不同的构建过程可以复用相同的部件组装方式。
创建者模式主要由五个部分构成:组装类,抽象创建者类,实现抽象创建者类的具体创建者类,抽象产品和实现抽象产品的具体产品类。
// Person 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 String getFoot() { return foot; } public void setFoot(String foot) { this.foot= foot; } public void setBody(String body) { this.body= body; } } //Builder接口 public interface PersonBuilder
{ void buildHead(); void buildBody(); void buildFoot(); Person buildPerson(); } //Builder实现:人类 publicclass HumanBuilder implements PersonBuilder
{ private Person person; public HumanBuilder()
{ this.person=new Person(); } public void buildBody()
{ this.person.setBody("创建 人类 身体!"); } publicvoid buildFoot()
{ this.person.setFoot("创建 人类 脚!"); } publicvoid buildHead() { this.person.setHead("创建 人类 头!"); } public Person buildPerson() { return person; } } //Builder实现:变形金刚 publicclass TransformerBuilder implements PersonBuilder { private Person person; public TransformerBuilder(){ this.person=newPerson(); } publicvoid buildBody() { this.person.setBody("创建 变形金刚 身体!"); } public void buildFoot() { this.person.setFoot("创建 变形金刚 脚!"); } publicvoid buildHead() { this.person.setHead("创建 变形金刚 头!"); } public Person buildPerson() { return person; } } //Director构建向导 publicclass PersonDirector
{ public Person constructPerson(PersonBuilder pb)
{ pb.buildHead(); pb.buildBody(); pb.buildFoot(); return pb.buildPerson(); } } //测试 publicclass Test
{ publicstaticvoid main(String[] args)
{ PersonDirector pd = new PersonDirector(); Person person = pd.constructPerson(new HumanBuilder()); System.out.println(person.getBody()); System.out.println(person.getFoot()); System.out.println(person.getHead() +" \n"); Person transformer = pd.constructPerson(newTransformerBuilder()); System.out.println(transformer.getBody()); System.out.println(transformer.getFoot()); System.out.println(transformer.getHead()); } }
标签:
原文地址:http://www.cnblogs.com/liujun5020/p/5462449.html