读Android Builder设计模式后实战

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010316858/article/details/50112725

Builder模式

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.

Builder 模式的使用场景

  • 相同的方法,不同的执行顺序,产生不同的事件结果时.
  • 多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不相同时.
  • 产品类非常复杂,或者产品类中的调用顺序不同产生了不同的作用,这个时候使用建造者模式非常合适.
  • 当初始化一个对象特别复杂,如参数多,且很多参数都具有默认值时.

例如


    package com.softtanck;
    /**
     * 
     * @author Tanck
     * 
     * @date 2015-11-30 14:08:39
     *
     */
    public class CarConfig {

        int wheels;// 轮子数

        int color;// 车的颜色

        int maxSeat;// 最多座位

        int maxSpeed;// 最快速度

        // 更多...

        private CarConfig() {
        }

        public static class Builder {

            private int wheels;// 轮子数

            private int color;// 车的颜色

            private int maxSeat;// 最多座位

            private int maxSpeed;// 最快速度

            // 更多...

            /**
             * 设置轮子
             * 
             * @param wheels
             * @return
             */
            public Builder setWheels(int wheels) {
                if (1 >= wheels)
                    wheels = 2;// 默认为2
                this.wheels = wheels;
                return this;
            }

            /**
             * 设置颜色
             * 
             * @param color
             */
            public Builder setColor(int color) {
                this.color = color;
                return this;
            }

            /**
             * 设置位置
             * 
             * @param maxSeat
             */
            public Builder setMaxSeat(int maxSeat) {
                if (4 <= maxSeat)
                    maxSeat = 4;// 默认为4
                this.maxSeat = maxSeat;
                return this;
            }

            /**
             * 设置速度
             * 
             * @param maxSpeed
             */
            public Builder setMaxSpeed(int maxSpeed) {
                this.maxSpeed = maxSpeed;
                return this;
            }

            /**
             * 应用配置
             * 
             * @param carConfig
             */
            private void applyConfig(CarConfig carConfig) {
                carConfig.color = this.color;
                carConfig.maxSeat = this.maxSeat;
                carConfig.maxSpeed = this.maxSpeed;
                carConfig.wheels = this.wheels;
            }

            public CarConfig create() {
                CarConfig carConfig = new CarConfig();
                applyConfig(carConfig);
                return carConfig;
            }

        }

    }

使用方式

CarConfig carConfig = new CarConfig.Builder()
                .setColor(1)
                .setMaxSeat(4)
                .setWheels(4)
                .setMaxSpeed(200).create();

优点

  • 良好的封装性,使用建造者模式可以使客服端不必知道产品内部组成的细节.
  • 建造者独立,容易扩展.

缺点

会产生多余的Builder对象以及Director对象,消耗内存.

猜你喜欢

转载自blog.csdn.net/u010316858/article/details/50112725