建造者模式

34 阅读1分钟

建造者模式是一种创建型模式,通常用来创建复杂型对象。

把组装一辆汽车看成由方向盘,轮胎,发动机,车架构成。下面用一个简单的代码例子说明用建造者模式构建一辆汽车。

public class Car {

    private Builder builder;

    private Car(Builder builder) {
        this.builder = builder;
    }

    public static class Builder {

        private String frame;

        private String wheel;

        private String tyre;

        private String motor;


        public Builder setFrame(String frame) {
            this.frame = frame;
            return this;
        }

        public Builder setWheel(String wheel) {
            this.wheel = wheel;
            return this;
        }

        public Builder setTyre(String tyre) {
            this.tyre = tyre;
            return this;
        }

        public Builder setMotor(String motor) {
            this.motor = motor;
            return this;
        }

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

        @Override
        public String toString() {
            return "Builder{" +
                    "frame='" + frame + ''' +
                    ", wheel='" + wheel + ''' +
                    ", tyre='" + tyre + ''' +
                    ", motor='" + motor + ''' +
                    '}';
        }
    }

    public Builder getBuilder() {
        return builder;
    }

@Test
public void test() {
    Car build = new Car.Builder().setFrame("车架name")
            .setMotor("发动机name")
            .setWheel("方向盘name").build();
    System.out.println(build.getBuilder());
}