前言
构造者模式:使用多个简单的对象,逐渐构建成一个复杂的对象。构造者模式属于创建型模式,它提供了一种创建对象的最佳方式
原文地址:https://xuedongyun.cn/post/24102/
实例
构造者模式包含以下角色:
- 抽象构造者(Builder)
- 具体构造者(ConcreteBuilder)
- 产品类(Product)
- 指挥者类(Director)
产品类:
1 2 3 4 5 6 7
| public class Phone { private String name; private String cpu; }
|
抽象构造者:
1 2 3 4 5 6 7 8 9 10
| public abstract class Builder {
protected Phone phone = new Phone();
public abstract void buildName();
public abstract void buildCpu();
public abstract Phone createPhone(); }
|
具体构造者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class ApplePhoneBuilder extends Builder{ @Override public void buildName() { phone.setName("iphone"); }
@Override public void buildCpu() { phone.setCpu("A14"); }
@Override public Phone createPhone() { return phone; } }
|
指挥者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Director { private Builder builder;
public Director(Builder builder) { this.builder = builder; } public Phone construct() { builder.buildName(); builder.buildCpu(); return builder.createPhone(); } }
|
使用:
1 2 3 4 5
| Builder builder = new AppleBuilder();
Director director = new Director(builder);
Phone phone = director.construct();
|
有时,可以把Director
和Builder
合二为一,简化系统结构。不过如果construct()
方法过于复杂,还是建议封装到Director
中
将Director
和Builder
合二为一
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public abstruct class Builder { protected Phone phone = new Phone(); public abstract void buildName(); public abstract void buildCpu(); public abstract Phone createPhone(); public Phone construct() { this.buildName(); this.buildCpu(); return this.phone; } }
|
模式扩展
建造者模式还有一个用途。如果类构造器需要传入很多参数时,可读性会很差,而且容易出错。此时就可以使用建造者模式重构。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class Computer {
public Computer(String cpu, String gpu, String motherboard) { this.cpu = cpu; this.gpu = gpu; this.motherboard = motherboard; }
private String cpu; private String gpu; private String motherboard;
public static class Builder { private String cpu; private String gpu; private String motherboard;
public Builder() {}
public Builder cpu(String cpu) { this.cpu = cpu; return this; }
public Builder gpu(String gpu) { this.gpu = gpu; return this; }
public Builder motherBoard(String motherboard) { this.motherboard = motherboard; return this; }
public Computer build() { return new Computer(cpu, gpu, motherboard); } } }
|
使用
1 2 3 4 5
| Computer computer = new Computer.Builder() .cpu("i9") .gpu("3060") .motherBoard("asus") .build();
|
与工厂模式对比
工厂方法模式 VS 建造者模式
- 工厂方法模式:注重对整体的创建方式
- 建造者模式:注重的是部件的创建过程
抽象工厂模式 VS 建造者模式