作者:夏至 欢饮转载,也请保留这段申明
http://blog.csdn.net/u011418943/article/details/60140099
首先,先看一下 okhttp 的数据初始化:
Request.Builder builder = new Request.Builder();
final Request request = builder
.get()
.url(url)
.build();
是不是结构清晰,感觉就很高大上呢?
不管你信不信,反正我信了;最近在搞一个下载器的项目,项目在添加下载任务的时候,我是不是也可以这样来初始化呢?所以研究了一下上面的那种实现方法,发现其实挺简单的。
其实就是在实体类中,提供一个静态类,里面再添加共有方法即可,如:
public class Taskinfo {
private String name; //文件名
private String url; //文件url
private int threadcount; //文需要的线程
public Taskinfo(Builder builder) {
this.name = builder.name;
this.url = builder.url;
this.threadcount = builder.threadcount;
}
public static class Builder{
private String name;
private String url;
private int threadcount;
public Builder setName(String name){
this.name = name;
return this;
}
public Builder setUrl(String url){
this.url = url;
return this;
}
public Builder setThreadcount(int threadcount){
this.threadcount = threadcount;
return this;
}
public Taskinfo build(){
return new Taskinfo(this);
}
}
@Override
public String toString() {
return "Taskinfo{" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", threadcount=" + threadcount +
'}';
}
}
我把 get 和 set 去掉了,然后你注意 Builder 类里面的方法就可以了。那么,我们的初始化就可以这样写了:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "zsr";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Taskinfo taskinfo = new Taskinfo.Builder()
.setName("有道词典")
.setUrl("www.baidu.com")
.setThreadcount(5)
.build();
Log.d(TAG, "onCreate: "+taskinfo);
}
}
打印如下:
D/zsr: onCreate: Taskinfo{name='有道词典', url='www.baidu.com', threadcount=5}
这样是不是感觉自己叼了很多,用了这种方式,是不是同事看到尖叫,老板看了直刷666。
不管你信不信,反正我还是信了。