建造者模式:用于dialog Glide等;
<pre>
public class Dialog {
private String name;
private String age;
private Dialog() {
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Dialog{");
sb.append("name='").append(name).append('\'');
sb.append(", age='").append(age).append('\'');
sb.append('}');
return sb.toString();
}
public static class Builder {
private static final String TAG = "Builder";
private Dialog dialog;
private String name;
private String age;
public Builder() {
dialog = new Dialog();
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(String age) {
this.age = age;
return this;
}
/**
* 根据值的有无和不同显示不同的效果
*
* @return 返回bulider
*/
public Builder create() {
if (age != null && !age.isEmpty()) {
dialog.age = age;
}
if (name != null && !name.isEmpty()) {
dialog.name = name;
}
Log.i(TAG, "create: " + dialog.toString());
return this;
}
public Dialog show() {
Dialog dialog = new Dialog();
this.apply(dialog);
Log.i(TAG, "create: " + dialog.toString());
return dialog;
}
public Dialog apply(Dialog dialog) {
dialog.name = this.name;
dialog.age = this.age;
return dialog;
}
public Builder apply(Builder builder) {
this.name = builder.name;
this.age = builder.age;
return builder;
}
}
}
</pre>
使用:
<pre>
Dialog.Builder builder = new Dialog.Builder().setAge("100").setName("张三").create();
Dialog.Builder builder_1 = new Dialog.Builder().apply(builder).create();
builder_1.setAge("99").create();
Dialog.Builder builder_2 = new Dialog.Builder().create();
Dialog dialog = new Dialog.Builder().apply(builder).show();
</pre>
log:
<pre>
02-28 20:23:19.284 9863-9863/com.lerz.builderdemo I/Builder: create: Dialog{name='张三', age='100'}
02-28 20:23:19.284 9863-9863/com.lerz.builderdemo I/Builder: create: Dialog{name='张三', age='100'}
02-28 20:23:19.284 9863-9863/com.lerz.builderdemo I/Builder: create: Dialog{name='张三', age='99'}
02-28 20:23:19.284 9863-9863/com.lerz.builderdemo I/Builder: create: Dialog{name='null', age='null'}
02-28 20:23:19.284 9863-9863/com.lerz.builderdemo I/Builder: create: Dialog{name='张三', age='99'}
</pre>