建造者模式,又称为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方法