Android Builder模式

Android 設計模式demo索引 Android 23種設計模式

前言

Builder模式是創建一個複雜對象的一種模式,此模式,用戶不用知道內部構建細節,可以更好的控制構建流程。一個複雜對象可以有很多參數、部件,Builder模式就是爲了將創建這個複雜對象的過程和對象的衆多參數部件分開,已達到解耦的目的。這樣構建過程和部件都可以自由擴展,兩者之間的耦合也降到最低。

Builder模式

將一個複雜對象的構建與對象的參數或部件的創建分離,使得同樣的創建過程可以有不同的結果。

例子

我們先來看一個簡單實現builder的例子。


public class Person  {
    private int ID;
    private int age;
    private String name;
    private int hight;
    private int weight;
    private Callback callback;

    interface Callback {
        void callback();
    }

    private Person(Builder builder) {
        this.ID = builder.ID;
        this.age = builder.age;
        this.name = builder.name;
        this.hight = builder.hight;
        this.weight = builder.weight;
        this.callback = builder.callback;
    }

    public static class Builder {
        private int ID;
        private int age;
        private String name;
        private int hight;
        private int weight;
        private Callback callback;

        public Builder setID(int ID) {
            this.ID = ID;
            return this;
        }

        public Builder setAge(int age) {
            this.age = age;
            return this;
        }

        public Builder setName(String name) {
            this.name = name;
            return this;
        }

        public Builder setHight(int hight) {
            this.hight = hight;
            return this;
        }

        public Builder setWeight(int weight) {
            this.weight = weight;
            return this;
        }

        public Builder setCallback(Callback callback) {
            this.callback = callback;
            return this;
        }

        public Person build() {
            return new Person(this);
        }
    }
}
Person.Builder buider = new Person.Builder();
buider.setAge(13);
buider.setName("jack");
Person jack = buider.build();

1、私有化構建方法,使其只能通過內部類Builder的build方法創建
2、靜態內部類作爲橋樑,可以設置所有參數
3、通過build的方法創建Person實例。
4、由於Builder這個橋樑,使得構建時可以設置不同參數,把構建和參數解耦。
5、創建實例後,參數不可再改。
6、隱藏了構建過程,我們還可以在構建過程中增加一些處理,這些處理都是隱藏的,比如我們計算age是否是小於等於18歲等。

總結

整體來說Builder模式比較簡單,核心就是隱藏構造方法,通過一個靜態內部類封裝構造。隱藏構建過程。
主要使用於對象比較複雜的時候, Android中我們使用最多的就是AlertDialog了。

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