1. 程式人生 > 其它 >設計模式-構造器模式

設計模式-構造器模式

類圖

實現程式碼

Director

class Director {
    private Builder builder;
    public Director(Builder builder) {
         this.builder = builder;
    }
    public void construct() {
        builder.buildPartA();
        builder.buildPartB();
    }
}

Builder.class

interface Builder {
    void buildPartA();
    void buildPartB();
    Product getResult();
}

BuilderA.class

class BuilderA implements Builder {
    private Product productA;
    public BuilderA(Product productA) {
        this.productA = productA;
    }

    public void buildPartA() {
        this.productA.setHead("型號1");
    }

    public void buildPartB() {
        this.productA.setBody("A工產生產");
    }

    public Product getResult() {
        return productA;
    }
}

Product.class

class Product {
    private String head;
    private String body;

    get set..
}

Test.class

public class TestBuilder {
    public static void main(String[] args) {
        BuilderA builderA = new BuilderA(new Product());
        Director director = new Director(builderA);
        director.construct();
        System.out.println(builderA.getResult());
    }
}