设计模式

构造者模式

2017-09-23  本文已影响122人  jfson_土豆

建造者模式是及其常用的一种设计模式,经常提现在一些开源的三方库中来进行return 当前对象进行链式调用,如果你要开源一个niubility 的库,那么学习一下建造者模式是非常有必要的。

// 忽略参数,看下如何使用
Retrofit retrofit = new Retrofit.Builder()
                .client(null)
                .baseUrl(null)
                .addConverterFactory(null)
                .addCallAdapterFactory(null)
                .build();
/**
 * Author: jfson
 * Create on:  2017/9/20
 * Description:
 */
public class Coffee {
    public String water;  //放多少水
    public String coffee; // 放多少咖啡
    public String ice;  // 多少冰
    public String suger; // 多少糖

    public Coffee() {
    }

    public Coffee(Coffee coffee) {
        if (coffee == null) {
            return;
        }
        this.water = coffee.water;
        this.coffee = coffee.coffee;
        this.ice = coffee.ice;
        this.suger = coffee.suger;
    }


    public static final class Builder {
        private Coffee mCoffee;

        public Builder() {
            mCoffee = new Coffee();
        }

        public Coffee.Builder setWater(String water){
            mCoffee.water = water;
            return Builder.this;
        }

        public Coffee.Builder setCoffee(String coffee){
            mCoffee.coffee = coffee;
            return Builder.this;
        }

        public Coffee.Builder setIce(String ice){
            mCoffee.ice = ice;
            return Builder.this;
        }

        public Coffee.Builder setSuger(String suger){
            mCoffee.suger = suger;
            return Builder.this;
        }

        public Coffee build(){
            return new Coffee(mCoffee);
        }
    }
}
Coffee coffee = new Coffee.Builder()
                .setCoffee("more")
                .setIce("no")
                .setSuger("no")
                .setWater("little")
                .build();
上一篇 下一篇

猜你喜欢

热点阅读