Android设计模式之建造者模式

建造者模式,又称为Builder模式,概念:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。在android开发中常见的有AlertDialog等

先看一种不用Builder模式的代码:

public class HttpRequest {

    private Uri requestUri;
    private String title;
    private String savePath;
    private String desc;

    public Uri getRequestUri() {
        return requestUri;
    }

    public void setRequestUri(Uri requestUri) {
        this.requestUri = requestUri;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSavePath() {
        return savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

以上代码是简单的javabean  要创建对象时,除了new一个对象,然后用set方法,或者重写构造函数,麻烦。然后我们看一下Builder模式的实现:

public class HttpRequest {

    private Uri requestUri;
    private String title;
    private String savePath;
    private String desc;

    public Uri getRequestUri() {
        return requestUri;
    }

    public void setRequestUri(Uri requestUri) {
        this.requestUri = requestUri;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSavePath() {
        return savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public static class Builder{
        private HttpRequest mRequest;

        public Builder (){
            mRequest = new HttpRequest();
        }

        public Builder setRequestUri(Uri requestUri) {
            mRequest.setRequestUri(requestUri);
            return this;
        }

        public Builder setTitle(String title) {
            mRequest.setTitle(title);
            return this;
        }

        public Builder setSavePath(String savePath) {
            mRequest.setSavePath(savePath);
            return this;
        }

        public Builder setDesc(String desc) {
            mRequest.setDesc(desc);
            return this;
        }

        public HttpRequest builder(){
            return mRequest;
        }

    }
}
这样在创建对象的时候,可以随意set成员变量,用法:

HttpRequest request = new HttpRequest.Builder().setRequestUri(Uri.parse("")).setDesc("").setSavePath("").setTitle("").builder();
可以随意的设置成员变量,不用些构造函数,繁琐的set方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xioateng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值