建造者模式(六)

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

二、角色
    1.Product 产品类:建造者最后要构建出来的复杂对象。
    2.Builder 抽象构建者:为创建一个复杂对象各个组建指定抽象接口,规范产品的组建。
    3.ConcreteBuilder 具体建造者:实现抽象类返回的所有方法,写法上一般方法会返回建造者本身,这样调用时候可以一直用“.”号一直调用其它方法了。
    4.Director 导演类:执行者,指导构建过程。

三、优点
    1.封装性。
    2.建造者独立,容易扩展,便于控制细节风险。

四、使用场景
    1.相同的方法,不同的执行顺序,产生不同的事件结果。
    2.产品类十分复杂,构造方法或者初始化方法参数过多。
    在《Effective Java》书中第二条,就提到“遇到多个构造器参数时要考虑用构建器”,其实这里的构建器就属于建造者模式,只是里面把四个角色都放到具体产品里面了。

五、实例

    也许看了以上众多概念后你还是一头雾水,所以我们最好还是来通过一个例子来了解建造者模式的使用与好处。

    下面借用 universal-image-loader 里面例子来分析一下:

public final class DisplayImageOptions {
 
    private final int imageResOnLoading;
    private final int imageResForEmptyUri;
    private final int imageResOnFail;
    private final Drawable imageOnLoading;
    private final Drawable imageForEmptyUri;
    private final Drawable imageOnFail;
    private final boolean resetViewBeforeLoading;
    private final boolean cacheInMemory;
    private final boolean cacheOnDisk;
    private final ImageScaleType imageScaleType;
    private final Options decodingOptions;
    private final int delayBeforeLoading;
    private final boolean considerExifParams;
    private final Object extraForDownloader;
    private final BitmapProcessor preProcessor;
    private final BitmapProcessor postProcessor;
    private final BitmapDisplayer displayer;
    private final Handler handler;
    private final boolean isSyncLoading;
 
    private DisplayImageOptions(Builder :) {
        imageResOnLoading = builder.imageResOnLoading;
        imageResForEmptyUri = builder.imageResForEmptyUri;
        imageResOnFail = builder.imageResOnFail;
        imageOnLoading = builder.imageOnLoading;
        imageForEmptyUri = builder.imageForEmptyUri;
        imageOnFail = builder.imageOnFail;
        resetViewBeforeLoading = builder.resetViewBeforeLoading;
        cacheInMemory = builder.cacheInMemory;
        cacheOnDisk = builder.cacheOnDisk;
        imageScaleType = builder.imageScaleType;
        decodingOptions = builder.decodingOptions;
        delayBeforeLoading = builder.delayBeforeLoading;
        considerExifParams = builder.considerExifParams;
        extraForDownloader = builder.extraForDownloader;
        preProcessor = builder.preProcessor;
        postProcessor = builder.postProcessor;
        displayer = builder.displayer;
        handler = builder.handler;
        isSyncLoading = builder.isSyncLoading;
    }
 
    public boolean shouldShowImageOnLoading() {
        return imageOnLoading != null || imageResOnLoading != 0;
    }
 
    public boolean shouldShowImageForEmptyUri() {
        return imageForEmptyUri != null || imageResForEmptyUri != 0;
    }
 
    public boolean shouldShowImageOnFail() {
        return imageOnFail != null || imageResOnFail != 0;
    }
 
    public boolean shouldPreProcess() {
        return preProcessor != null;
    }
 
    public boolean shouldPostProcess() {
        return postProcessor != null;
    }
 
    public boolean shouldDelayBeforeLoading() {
        return delayBeforeLoading > 0;
    }
 
    public Drawable getImageOnLoading(Resources res) {
        return imageResOnLoading != 0 ? res.getDrawable(imageResOnLoading) : imageOnLoading;
    }
 
    public Drawable getImageForEmptyUri(Resources res) {
        return imageResForEmptyUri != 0 ? res.getDrawable(imageResForEmptyUri) : imageForEmptyUri;
    }
 
    public Drawable getImageOnFail(Resources res) {
        return imageResOnFail != 0 ? res.getDrawable(imageResOnFail) : imageOnFail;
    }
 
    public boolean isResetViewBeforeLoading() {
        return resetViewBeforeLoading;
    }
 
    public boolean isCacheInMemory() {
        return cacheInMemory;
    }
 
    public boolean isCacheOnDisk() {
        return cacheOnDisk;
    }
 
    public ImageScaleType getImageScaleType() {
        return imageScaleType;
    }
 
    public Options getDecodingOptions() {
        return decodingOptions;
    }
 
    public int getDelayBeforeLoading() {
        return delayBeforeLoading;
    }
 
    public boolean isConsiderExifParams() {
        return considerExifParams;
    }
 
    public Object getExtraForDownloader() {
        return extraForDownloader;
    }
 
    public BitmapProcessor getPreProcessor() {
        return preProcessor;
    }
 
    public BitmapProcessor getPostProcessor() {
        return postProcessor;
    }
 
    public BitmapDisplayer getDisplayer() {
        return displayer;
    }
 
    public Handler getHandler() {
        return handler;
    }
 
    boolean isSyncLoading() {
        return isSyncLoading;
    }
 
    /**
     * Builder for {@link DisplayImageOptions}
     *
     * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
     */
    public static class Builder {
        private int imageResOnLoading = 0;
        private int imageResForEmptyUri = 0;
        private int imageResOnFail = 0;
        private Drawable imageOnLoading = null;
        private Drawable imageForEmptyUri = null;
        private Drawable imageOnFail = null;
        private boolean resetViewBeforeLoading = false;
        private boolean cacheInMemory = false;
        private boolean cacheOnDisk = false;
        private ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2;
        private Options decodingOptions = new Options();
        private int delayBeforeLoading = 0;
        private boolean considerExifParams = false;
        private Object extraForDownloader = null;
        private BitmapProcessor preProcessor = null;
        private BitmapProcessor postProcessor = null;
        private BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer();
        private Handler handler = null;
        private boolean isSyncLoading = false;
 
        /**
         * Stub image will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} during image loading
         *
         * @param imageRes Stub image resource
         * @deprecated Use {@link #showImageOnLoading(int)} instead
         */
        @Deprecated
        public Builder showStubImage(int imageRes) {
            imageResOnLoading = imageRes;
            return this;
        }
 
        /**
         * Incoming image will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} during image loading
         *
         * @param imageRes Image resource
         */
        public Builder showImageOnLoading(int imageRes) {
            imageResOnLoading = imageRes;
            return this;
        }
 
        /**
         * Incoming drawable will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} during image loading.
         * This option will be ignored if {@link DisplayImageOptions.Builder#showImageOnLoading(int)} is set.
         */
        public Builder showImageOnLoading(Drawable drawable) {
            imageOnLoading = drawable;
            return this;
        }
 
        /**
         * Incoming image will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} if empty URI (null or empty
         * string) will be passed to <b>ImageLoader.displayImage(...)</b> method.
         *
         * @param imageRes Image resource
         */
        public Builder showImageForEmptyUri(int imageRes) {
            imageResForEmptyUri = imageRes;
            return this;
        }
 
        /**
         * Incoming drawable will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} if empty URI (null or empty
         * string) will be passed to <b>ImageLoader.displayImage(...)</b> method.
         * This option will be ignored if {@link DisplayImageOptions.Builder#showImageForEmptyUri(int)} is set.
         */
        public Builder showImageForEmptyUri(Drawable drawable) {
            imageForEmptyUri = drawable;
            return this;
        }
 
        /**
         * Incoming image will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} if some error occurs during
         * requested image loading/decoding.
         *
         * @param imageRes Image resource
         */
        public Builder showImageOnFail(int imageRes) {
            imageResOnFail = imageRes;
            return this;
        }
 
        /**
         * Incoming drawable will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} if some error occurs during
         * requested image loading/decoding.
         * This option will be ignored if {@link DisplayImageOptions.Builder#showImageOnFail(int)} is set.
         */
        public Builder showImageOnFail(Drawable drawable) {
            imageOnFail = drawable;
            return this;
        }
 
        /**
         * {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} will be reset (set <b>null</b>) before image loading start
         *
         * @deprecated Use {@link #resetViewBeforeLoading(boolean) resetViewBeforeLoading(true)} instead
         */
        public Builder resetViewBeforeLoading() {
            resetViewBeforeLoading = true;
            return this;
        }
 
        /**
         * Sets whether {@link com.nostra13.universalimageloader.core.imageaware.ImageAware
         * image aware view} will be reset (set <b>null</b>) before image loading start
         */
        public Builder resetViewBeforeLoading(boolean resetViewBeforeLoading) {
            this.resetViewBeforeLoading = resetViewBeforeLoading;
            return this;
        }
 
        /**
         * Loaded image will be cached in memory
         *
         * @deprecated Use {@link #cacheInMemory(boolean) cacheInMemory(true)} instead
         */
        @Deprecated
        public Builder cacheInMemory() {
            cacheInMemory = true;
            return this;
        }
 
        /** Sets whether loaded image will be cached in memory */
        public Builder cacheInMemory(boolean cacheInMemory) {
            this.cacheInMemory = cacheInMemory;
            return this;
        }
 
        /**
         * Loaded image will be cached on disk
         *
         * @deprecated Use {@link #cacheOnDisk(boolean) cacheOnDisk(true)} instead
         */
        @Deprecated
        public Builder cacheOnDisc() {
            return cacheOnDisk(true);
        }
 
        /**
         * Sets whether loaded image will be cached on disk
         *
         * @deprecated Use {@link #cacheOnDisk(boolean)} instead
         */
        @Deprecated
        public Builder cacheOnDisc(boolean cacheOnDisk) {
            return cacheOnDisk(cacheOnDisk);
        }
 
        /** Sets whether loaded image will be cached on disk */
        public Builder cacheOnDisk(boolean cacheOnDisk) {
            this.cacheOnDisk = cacheOnDisk;
            return this;
        }
 
        /**
         * Sets {@linkplain ImageScaleType scale type} for decoding image. This parameter is used while define scale
         * size for decoding image to Bitmap. Default value - {@link ImageScaleType#IN_SAMPLE_POWER_OF_2}
         */
        public Builder imageScaleType(ImageScaleType imageScaleType) {
            this.imageScaleType = imageScaleType;
            return this;
        }
 
        /** Sets {@link Bitmap.Config bitmap config} for image decoding. Default value - {@link Bitmap.Config#ARGB_8888} */
        public Builder bitmapConfig(Bitmap.Config bitmapConfig) {
            if (bitmapConfig == null) throw new IllegalArgumentException("bitmapConfig can't be null");
            decodingOptions.inPreferredConfig = bitmapConfig;
            return this;
        }
 
        /**
         * Sets options for image decoding.<br />
         * <b>NOTE:</b> {@link Options#inSampleSize} of incoming options will <b>NOT</b> be considered. Library
         * calculate the most appropriate sample size itself according yo {@link #imageScaleType(ImageScaleType)}
         * options.<br />
         * <b>NOTE:</b> This option overlaps {@link #bitmapConfig(android.graphics.Bitmap.Config) bitmapConfig()}
         * option.
         */
        public Builder decodingOptions(Options decodingOptions) {
            if (decodingOptions == null) throw new IllegalArgumentException("decodingOptions can't be null");
            this.decodingOptions = decodingOptions;
            return this;
        }
 
        /** Sets delay time before starting loading task. Default - no delay. */
        public Builder delayBeforeLoading(int delayInMillis) {
            this.delayBeforeLoading = delayInMillis;
            return this;
        }
 
        /** Sets auxiliary object which will be passed to {@link ImageDownloader#getStream(String, Object)} */
        public Builder extraForDownloader(Object extra) {
            this.extraForDownloader = extra;
            return this;
        }
 
        /** Sets whether ImageLoader will consider EXIF parameters of JPEG image (rotate, flip) */
        public Builder considerExifParams(boolean considerExifParams) {
            this.considerExifParams = considerExifParams;
            return this;
        }
 
        /**
         * Sets bitmap processor which will be process bitmaps before they will be cached in memory. So memory cache
         * will contain bitmap processed by incoming preProcessor.<br />
         * Image will be pre-processed even if caching in memory is disabled.
         */
        public Builder preProcessor(BitmapProcessor preProcessor) {
            this.preProcessor = preProcessor;
            return this;
        }
 
        /**
         * Sets bitmap processor which will be process bitmaps before they will be displayed in
         * {@link com.nostra13.universalimageloader.core.imageaware.ImageAware image aware view} but
         * after they'll have been saved in memory cache.
         */
        public Builder postProcessor(BitmapProcessor postProcessor) {
            this.postProcessor = postProcessor;
            return this;
        }
 
        /**
         * Sets custom {@link BitmapDisplayer displayer} for image loading task. Default value -
         * {@link DefaultConfigurationFactory#createBitmapDisplayer()}
         */
        public Builder displayer(BitmapDisplayer displayer) {
            if (displayer == null) throw new IllegalArgumentException("displayer can't be null");
            this.displayer = displayer;
            return this;
        }
 
        Builder syncLoading(boolean isSyncLoading) {
            this.isSyncLoading = isSyncLoading;
            return this;
        }
 
        /**
         * Sets custom {@linkplain Handler handler} for displaying images and firing {@linkplain ImageLoadingListener
         * listener} events.
         */
        public Builder handler(Handler handler) {
            this.handler = handler;
            return this;
        }
 
        /** Sets all options equal to incoming options */
        public Builder cloneFrom(DisplayImageOptions options) {
            imageResOnLoading = options.imageResOnLoading;
            imageResForEmptyUri = options.imageResForEmptyUri;
            imageResOnFail = options.imageResOnFail;
            imageOnLoading = options.imageOnLoading;
            imageForEmptyUri = options.imageForEmptyUri;
            imageOnFail = options.imageOnFail;
            resetViewBeforeLoading = options.resetViewBeforeLoading;
            cacheInMemory = options.cacheInMemory;
            cacheOnDisk = options.cacheOnDisk;
            imageScaleType = options.imageScaleType;
            decodingOptions = options.decodingOptions;
            delayBeforeLoading = options.delayBeforeLoading;
            considerExifParams = options.considerExifParams;
            extraForDownloader = options.extraForDownloader;
            preProcessor = options.preProcessor;
            postProcessor = options.postProcessor;
            displayer = options.displayer;
            handler = options.handler;
            isSyncLoading = options.isSyncLoading;
            return this;
        }
 
        /** Builds configured {@link DisplayImageOptions} object */
        public DisplayImageOptions build() {
            return new DisplayImageOptions(this);
        }
    }
 
    /**
     * Creates options appropriate for single displaying:
     * <ul>
     * <li>View will <b>not</b> be reset before loading</li>
     * <li>Loaded image will <b>not</b> be cached in memory</li>
     * <li>Loaded image will <b>not</b> be cached on disk</li>
     * <li>{@link ImageScaleType#IN_SAMPLE_POWER_OF_2} decoding type will be used</li>
     * <li>{@link Bitmap.Config#ARGB_8888} bitmap config will be used for image decoding</li>
     * <li>{@link SimpleBitmapDisplayer} will be used for image displaying</li>
     * </ul>
     * <p/>
     * These option are appropriate for simple single-use image (from drawables or from Internet) displaying.
     */
    public static DisplayImageOptions createSimple() {
        return new Builder().build();
    }
}

    虽然这个有点长,但是结构还是很清新明了的。

    首先我们可以看到我们需要一个 DisplayImageOptions 的对象类,但是这个类需要配置的信息众多(63-75行),如果全都由构造方法传入的话显然不可能,这里使用了建造者模式来完成 DisplayImageOptions 对象类的构建。

    这里的建造者是一个静态内部类 DisplayImageOptions.Builder,担任了建造者模式中抽象建造者和具体建造者两个职责。由 build() 方法返回构建的 DisplayImageOptions 实例,其余方法负责具体组件的配置并返回 Builder 对象,于是我们可以像下面这样调用:

DisplayImageOptions options = new DisplayImageOptions.Builder()
        .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
        .cacheOnDisk(true) // 设置下载的图片是否缓存在本地中
        .showImageForEmptyUri(R.mipmap.icon_head) // 空的Uri时显示的图片
        .showImageOnFail(R.mipmap.icon_head) // 错误时显示的图片
        .showImageOnLoading(R.mipmap.icon_head) // 加载时显示的图片
        .build();

    这样使用起来是不是十分简单和清晰了呢。


查看更多:设计模式分类以及六大设计原则

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值