1

描述:一个复杂的对象由多个部件组成,每个部件可以独立生成,部件的组装过程交由指引者完成。

场景:假设宏基笔记本仅由CPU和内存组成,其中生产CPU和内存的工序可以独立出来交由各个OEM厂商制造。

实现:

笔记本:

class AcerComputer {
    String cpu;
    String memory;
    AcerComputer(String cpu, String memory) {
        this.cpu = cpu;
        this.memory = memory;
    }
}

定义一个建造者:

interface Builder {
    public String createCPU();
    public String createMemory();
}

定义一个OEM,负责生成CPU、内存:

class OEM implements Builder {
    @Override
    public String createCPU() {
        return "CPU";
    }
    @Override
    public String createMemory() {
        return "内存";
    }
}

定义宏基公司,下定单让OEM制造CPU和内存,它自己组装成电脑:

class AcerCompany {
    private Builder builder;
    private String name;
    AcerCompany(Builder builder) {
        this.builder = builder;
        this.name = "宏基公司";
    }
    public AcerComputer create() {
        String cpu = builder.createCPU();
        String memory = builder.createMemory();
        return new AcerComputer(cpu, memory);
    }
}

客户端调用:

public static void main(String[] args) {
    Builder builder = new OEM();
    AcerCompany acerCompany = new AcerCompany(builder);
    // 宏基电脑出厂了
    AcerComputer computer = acerCompany.create();
}

==============邪恶的分割线==========================================

利用建造者模式写构造方法:

如果一个对象的构造参数非常多,可以考虑使用建造者模式构造参数,从而使得构造的过程更加语义化。

举个“萝卜”,我们要构造一头猪,它的属性有雌雄、年龄、品种、肤色等。具体代码如下:

class Pig {
    String sex;
    int age;
    String varieties; // 品种
    String color; 
    // 普通方法实现
    Pig(String sex, int age, String varieties, String color) {
        this.sex = sex;
        this.age = age;
        this.varieties = varieties;
        this.color = color;
    }
    // 建造者模式实现
    Pig(Builder builder) {
        this.sex = builder.sex;
        this.age = builder.age;
        this.color = builder.color;
        this.varieties = builder.varieties;
    }
    // 内部类实现建造者
    static class Builder {
        String sex;
        int age;
        String varieties; // 品种
        String color; 
        public Builder sex(String sex) {
            this.sex = sex;
            return this;
        }
        public Builder age(int age) {
            this.age = age;
            return this;
        }
        public Builder varieties(String varieties) {
            this.varieties = varieties;
            return this;
        }
        public Builder color(String color) {
            this.color = color;
            return this;
        }
        public Pig build() {
            return new Pig(this);
        }
    }
}

客户端调用,语义化跃然纸上。

public static void main(String[] args) {
    // 普通方法实现
    Pig pig1 = new Pig("母", 10, "一号土猪", "黑色");
    // 建造者模式实现
    Pig pig2 = new Pig.Builder().sex("公").age(5).varieties("黑珍珠").color("白色").build();
}

k00baa
325 声望16 粉丝

BUG