android设计模式二十三式(三)——建造者模式(Builder)

Build模式/建造者模式

Build模式,在开发中非常常见,也很实用,最常见的,就是创建Dialog的时候,用起来,有点像链式调用,看一下我用build模式写的一个Data对象的调用方法。


创建一个Data对象

 Data data = new Data.Builder()
                .category(getCategory())
                .owner(getOwner())
                .content(getContent())
                .keys(getKeys())
                .uuid(uuid)
                .build();

这样就可以了,省去了繁琐的set方法,也不用在Data对象中写入繁琐的不同的有参构造函数来创建对象,有了build类,我们可以随意传入参数个数,调用build方法建造出一个对象。

静态内部类的Build对象,避免了内部类对外部类引用从而导致内存泄漏,静态内部类的生命周期,和普通类一样,new出来创建,系统回收,注意处理好静态内部类的静态成员变量引用,建议静态内部类中不要写静态的成员变量。

public class Data {
    private String uuid,owner,category,content;
    private Keys keys;

    public Data() {

    }

    private Data(Builder builder) {
        this.uuid = builder.uuid;
        this.owner = builder.owner;
        this.category = builder.category;
        this.content = builder.content;
        this.keys = builder.keys;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Keys getKeys() {
        return keys;
    }

    public void setKeys(Keys keys) {
        this.keys = keys;
    }

    public static class Builder {
        private String uuid,owner,category,content;
        private Keys keys;

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

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

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

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

        public Builder keys(Keys keys){
            this.keys = keys;
            return this;
        }

        public Data build() {
            return new Data(this);
        }
    }
}

你可能感兴趣的:(android,设计模式)