标签:person ldb over his rect xtend on() pre builder
建造者模式:
将一个复杂对象的构建和表示分离,使得同样的构建过程可以创建不同的表示。使用建造者模式,用户只要指定类型就可以得到他们,不需要关心建造的过程和细节。
组成:
适用性:
类图:
代码:
public class Person { private String head; private String body; private String hands; private String feet; 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 getHands() { return hands; } public void setHands(String hands) { this.hands = hands; } public String getFeet() { return feet; } public void setFeet(String feet) { this.feet = feet; } }
public class Man extends Person { public Man() { System.out.println("创建男人"); } }
public class Woman extends Person { public Woman() { System.out.println("开始创建女人"); } }
public abstract class Builder { abstract void buildHead(); abstract void buildBody(); abstract void buildHands(); abstract void buildFeet(); abstract Person buildPerson(); }
public class ManBuilder extends Builder{ private Man man; public ManBuilder() { this.man = new Man(); } @Override void buildHead() { System.out.println("创建男人头部"); man.setHead("创建男人头部"); } @Override void buildBody() { System.out.println("创建男人身体"); man.setBody("创建男人身体"); } @Override void buildHands() { System.out.println("创建男人双手"); man.setHands("创建男人双手"); } @Override void buildFeet() { System.out.println("创建男人双脚"); man.setFeet("创建男人手脚"); } @Override Person buildPerson() { return man; } }
public class WomanBuilder extends Builder{ private Woman woman; public WomanBuilder() { this.woman = new Woman(); } @Override void buildHead() { System.out.println("创建女人头部"); woman.setHead("创建女人头部"); } @Override void buildBody() { System.out.println("创建女人身体"); woman.setBody("创建女人身体"); } @Override void buildHands() { System.out.println("创建女人双手"); woman.setHands("创建女人双手"); } @Override void buildFeet() { System.out.println("创建女人双脚"); woman.setFeet("创建女人手脚"); } @Override Person buildPerson() { return woman; } }
public class Director { public Person construct(Builder builder){ builder.buildHead(); builder.buildBody(); builder.buildFeet(); builder.buildHands(); return builder.buildPerson(); } public static void main(String[] args) { Director director = new Director(); director.construct(new ManBuilder()); } }
标签:person ldb over his rect xtend on() pre builder
原文地址:http://www.cnblogs.com/foreverYoungCoder/p/7831823.html