建造者(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方法吧。。



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