Builder 模式 - 对应多个构造器参数

问题

当我们拥有一个类,它有几个必需成员变量和几个可选成员变量,如何构建这个类的实例,才能保证构建过程可读和安全?

现有方法的痛处

  • 重叠构造器:

    1. 必须提供大量的构造器,不然会出现填写本不想设置的参数的情况
    2. 从方法的调用很难看出每个参数的含义
  • JavaBeans 模式的 setter 方法:
    整个构造过程被划分到多个调用之中,因此

    1. 无法通过仅仅观察构造器参数了解类的成员
    2. 需要做额外的工作保证其线程安全

Builder 模式

假设 Player 类的必需成员为 height, weight,可选成员为 strength, speed, skill,则该类的 Builder 模式如下:

// Builder Pattern
public class Player {
    private final double height;
    private final double weight;
    private final double strength;
    private final double speed;
    private final double skill;

    public static class Builder {
        // Required parameters
        private final double height;
        private final double weight;

        // Optional parameters - initialized to default values
        private double strength = 0;
        private double speed    = 0;
        private double skill    = 0;

        public Builder(double height, double weight) {
            this.height = height;
            this.weight = weight;
        }

        public Builder strength(double val) {
            strength = val;
            return this;
        }

        public Builder speed(double val) {
            speed = val;
            return this;
        }

        public Builder skill(double val) {
            skill = val;
            return this;
        }

        public Player build() {
            return new Player(this);
        }
    }

    private Player(Builder builder) {
        height      = builder.height;
        weight      = builder.weight;
        strength    = builder.strength;
        speed       = builder.speed;
        skill       = builder.skill;
    }
}

调用如下:

Player player = new Player.Builder(198, 120)
                        .speed(80)
                        .skill(95)
                        .build();

你可能感兴趣的:(Java)