看源码模仿--Builder模式

         今天在研究Okhttp源码,看到Request类时发现该类使用Builder模式来构建Request,还有HttpUrl 、Okhttp等也使用了构建模式。

以下是根据Okhttp源码中的Request类模仿的模式。

package com.zghw.ack;

/**
 * Created by zhanghw on 2017/9/7.
 * Builder模式构建Request请求对象
 * 为了可以在多线程中使用,定义为不可变类
 * 这个方式在builder 构造好对象后,Request不可变。
 */
public final class Request {
    final String method;
    final String url;

    //不提供默认new方法,让内部静态类Builder构建,主要进行copy
    Request(Builder builder) {
        this.method = builder.method;
        this.url = builder.url;
    }

    //仅提供读方法
    public String getMethod() {
        return method;
    }

    //仅提供读方法
    public String getUrl() {
        return url;
    }

    /**
     * 重新构建一个Builder对象,把当前request深度拷贝到新的对象中,
     * 然后调用builder 修改或追加组件。
     *
     * @return
     */
    public Builder newBuilder() {
        return new Builder(this);
    }

    public static class Builder {
        //字段一般和Request字段一样便于构建
        String method;
        String url;

        //提供默认构造方法,创建对象一遍构建request
        public Builder() {
            this.method = "GET";
        }

        //构造是用来拷贝的已有的
        Builder(Request request) {
            this.method = request.method;
            this.url = request.url;
        }

        //构建组件method
        public Builder method(String method) {
            this.method = method;
            //返回当前Builder对象
            return this;
        }

        //构建组件url
        public Builder url(String url) {
            this.url = url;
            return this;
        }

        //组件构建最后构建Request,这里是把当前builder对象拷贝到Request对象中。
        public Request build() {
            if (url == null) {
                throw new NullPointerException("url==null");
            }
            return new Request(this);
        }
    }

    public static void main(String args[]) {
        //链条式构建
        Request request = new Request.Builder().method("POST").url("http:www.baidu.com").build();
        //使用request重新构建一个新的Request对象,不存在添加或修改组件。
        Request requestNew = request.newBuilder().method("DELETE").build();
        System.out.println(request.toString() + "=" + request.getMethod() + "  " + request.getUrl() + " , " + requestNew.toString() + "=" + requestNew.getUrl() + "  " + requestNew.getMethod());
    }

}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值