利用靜態(tài)內(nèi)部類實現(xiàn)建造者模式恢口,建造者模式是用靜態(tài)內(nèi)部類創(chuàng)建外部類對象屑宠,將整個建造過程和用戶看到的界面分開來困檩。
程序中還會出現(xiàn)鏈式編程,要清楚鏈式編程的概念飒焦。
Weixin類:
重點1.在每個set方法會返回當前對象蜈膨,這樣才能實現(xiàn)鏈式編程屿笼。
? ? ? ?2.在最后會返回new ?Weixin(this) ?調(diào)用Weixin類的構(gòu)造方法。
? ? ?此處和普通的 Weixin ?weixin = new Weixin()翁巍;一個道理
package lianxi;
public class Weixin {
String name;
private String pswd;
private int age;
public Weixin(String name, String pswdString, int age) {
this.name = name;
this.pswd = pswdString;
this.age = age;
}
public Weixin(Build build) {
this.name = build.name;
this.pswd = build.pswdString;
this.age = build.age;
}
public Weixin() {
}
static class Build{
private String name;
private String pswdString;
private int age;
public Build(String name, String pswdString, int age) {
super();
this.name = name;
this.pswdString = pswdString;
this.age = age;
}
public String getName() {
return name;
}
public Build setName(String name) {
this.name = name;
return this;
}
public String getPswdString() {
return pswdString;
}
public? Build setPswdString(String pswdString) {
this.pswdString = pswdString;
return this;
}
public int getAge() {
return age;
}
public? Build setAge(int age) {
this.age = age;
return this;
}
@Override
public String toString() {
return "Inner [name=" + name + ", pswdString=" + pswdString
+ ", age=" + age + "]";
}
public Weixin build(){
return new Weixin(this);//會調(diào)用外部類Weixin的構(gòu)造方法
}
}
}
main:
package lianxi;
import lianxi.Weixin.Build;
public class Test2 {
public static void main(String[] args) {
//Weixin weixin = new Weixin("lxm","123456",22);
Build build = new Build("lxm","123456",22);
Weixin weixin = build.build();//
//利用鏈式編程實現(xiàn)重新賦值或修改值
build.setName("lmm").setPswdString("111").setAge(15);
System.out.println(build);
//還可以這樣
Weixin weixin2 = new Build("","",0).setName("sss").setAge(26).setPswdString("5656").build();
}
}
1.明白建造者是怎么一種設(shè)計模式
2.利用鏈式編程可以簡化代碼驴一,給屬性賦值或者改變值