构建Builder模式的原因是什么?

Mat*_*sis 0 java design-patterns

您好,我对构建模式有几个问题?

  1. 为什么主类中的实例变量是私有的?
  2. 为什么内部类声明为静态?
  3. 为什么内部类中的实例变量是私有的并且重复?
  4. 我们在方法中返回Builder对象究竟包含在这个对象中的什么内容?
  5. 为什么主构造函数是私有的?
public class Plank {
    //1. Why are these instance variables private?
    private double widthInches;
    private double heightInches;
    private double thicknessInches;

    //2. Why is this class static?
    public static class Builder {
        //Why are these instance variables private and repeated?
        private double widthInches;
        private double heightInches;
        private double thicknessInches;

        public Builder widthInches(double inches) {

            widthInches = inches;
            //3. What is returned here what object is this referencing?
            return this;

        }
        public Builder heightInches(double inches) {
            heightInches = inches;
            return this;
        }
        public Builder thicknessInches(double inches) {
            thicknessInches = inches;
            return this;
        }
        public Plank build() {
            return new Plank(this);
        }
    }
    //4. Why is this constructor private?
    private Plank(Builder build) {
        widthInches = build.widthInches;
        heightInches = build.heightInches;
        thicknessInches = build.thicknessInches;
    }

}
Run Code Online (Sandbox Code Playgroud)

And*_*eas 6

首先,阅读构建器模式.

为什么主类中的实例变量是私有的?

因为实例变量应该private(或protected)以防止不受信任的代码直接操纵.

为什么内部类声明为静态?

因为构建器需要在构建类之前构造,即外部类.

为什么内部类中的实例变量是私有的并且重复?

因为(见第一个答案)和(见第二个答案).

我们在方法中返回Builder对象究竟包含在这个对象中的什么内容?

从setter方法返回构建器对象允许方法链接.

为什么主构造函数是私有的?

因此,类只能由构建器实例化.