建造者(Builder)模式

附加--对讨厌你的人最好的反击是,保持微笑和光芒四射,他们最不希望看到这样的你


这模式也是使用多个简单的对象构建成一个复杂的对象,将变与不变分离开,我用到过也是对某个类进行相对应的配置,当然你也可以根据你的需求使用这模式,也就你需要生成的对象具有复杂的内部结构,或者需要生成的对象内部属性本身相互依赖,下面就举个简单例子吧。

其实很简单,就创建个配置类,添加你所需要的属性,列举代码则是对网络配置,只供参考,如下:

public class NetConfigBuilder {

    private File response_cache;
    private int response_cache_size = 5 * 1024 * 1024;
    private int connect_timeout = 8 * 1000;
    private int read_timeout = 5 * 1000;
    private Context appContext;
    private int maxCacheAge = 0;

    /**
     * request cache-control
     */
    public NetConfigBuilder maxCacheAge(int maxCacheAge) {
        this.maxCacheAge = maxCacheAge;
        return this;
    }

    /**
     * local cache dir
     */
    public NetConfigBuilder responseCacheDir(File response_cache) {
        this.response_cache = response_cache;
        return this;
    }

    /**
     * local cache size
     */
    public NetConfigBuilder responseCacheSize(int response_cache_size) {
        this.response_cache_size = response_cache_size;
        return this;
    }

    /**
     * readTime
     *
     * @param connect_timeout millisecond
     */
    public NetConfigBuilder connectionTimeout(int connect_timeout) {
        this.connect_timeout = connect_timeout;
        return this;
    }

    /**
     * timeout
     *
     * @param read_timeout millisecond
     */
    public NetConfigBuilder readTimeout(int read_timeout) {
        this.read_timeout = read_timeout;
        return this;
    }

    /**
     * must set Context
     */
    public NetConfigBuilder context(Context app) {
        this.appContext = app.getApplicationContext();
        return this;
    }

    public NetConfig createNetConfig() {
        return new NetConfig(response_cache, response_cache_size, connect_timeout, read_timeout, maxCacheAge, appContext);
    }
}

接下来就是使用了 ,你可以对其进行配置,设置属性,构建出一个属于你的对象,然后应用到你所需要的地方

/**
 * net config
 */
final NetConfig netConfig = new NetConfigBuilder()
        .context(this)
        .responseCacheDir(new File(context.getCacheDir(),"mycache"))
        .responseCacheSize(1024 * 1024 * 100)
        .readTimeout(2000)
        .createNetConfig();

是不是对这配置感觉看起来爽歪歪,不管你有没有,反正我有爽到,这在我构建对象时碰到类有很多参数,其中很多参数类型相同且很多参数可以为空时我就很喜欢用这模式来实现。不过相对的来说,当参数数量不多、类型不同而且都是必须出现时,通过增加代码实现Builder模式往往无法体现他的优势,这种情况下,通常都是调用传统的构造函数。再者,如果不需要保持不变,那么就直接使用无参构造函数调用相应的set方法吧。。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章