标签:优缺点 col 完整 create 包括 生产 code struct url
class Product { private String partA; //定义部件,部件可以是任意类型,包括值类型和引用类型 private String partB; private String partC; //partA的Getter方法和Setter方法省略 //partB的Getter方法和Setter方法省略 //partC的Getter方法和Setter方法省略 }
abstract class Builder { //创建产品对象 protected Product product=new Product(); public abstract void buildPartA(); public abstract void buildPartB(); public abstract void buildPartC(); //返回产品对象 public Product getResult() { return product; } }
class Director { private Builder builder; public Director(Builder builder) { this.builder=builder; } public void setBuilder(Builder builder) { this.builder=builer; } //产品构建与组装方法 public Product construct() { builder.buildPartA(); builder.buildPartB(); builder.buildPartC(); return builder.getResult(); } }
public class Client{ public static void main(String[] args){ Builder builder = new ConcreteBuilder(); //可通过配置文件实现 Director director = new Director(builder); Product product = director.construct(); } }
abstract class ActorBuilder { protected static Actor actor = new Actor(); public abstract void buildType(); public abstract void buildSex(); public abstract void buildFace(); public abstract void buildCostume(); public abstract void buildHairstyle(); public static Actor construct(ActorBuilder ab) { ab.buildType(); ab.buildSex(); ab.buildFace(); ab.buildCostume(); ab.buildHairstyle(); return actor; } }
abstract class ActorBuilder { protected Actor actor = new Actor(); public abstract void buildType(); public abstract void buildSex(); public abstract void buildHairstyle(); //钩子方法 public boolean isBareheaded() { return false; } public Actor createActor() { return actor; } } class DevilBuilder extends ActorBuilder { public void buildType() { actor.setType("恶魔"); } public void buildSex() { actor.setSex("妖"); } public void buildHairstyle() { actor.setHairstyle("光头"); } //覆盖钩子方法 public boolean isBareheaded() { return true; } } class ActorController { public Actor construct(ActorBuilder ab) { Actor actor; ab.buildType(); ab.buildSex(); //通过钩子方法来控制产品的构建 if (!ab.isBareheaded()) { ab.buildHairstyle(); } actor = ab.createActor(); return actor; } }
*****************************************参考************************************
标签:优缺点 col 完整 create 包括 生产 code struct url
原文地址:https://www.cnblogs.com/stanwuc/p/10897903.html