利用静态内部类实现建造者模式,建造者模式是用静态内部类创建外部类对象,将整个建造过程和用户看到的界面分开来。
程序中还会出现链式编程,要清楚链式编程的概念。
Weixin类:
重点1.在每个set方法会返回当前对象,这样才能实现链式编程。
2.在最后会返回new Weixin(this) 调用Weixin类的构造方法。
此处和普通的 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);//会调用外部类Weixin的构造方法
}
}
}
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();//
//利用链式编程实现重新赋值或修改值
build.setName("lmm").setPswdString("111").setAge(15);
System.out.println(build);
//还可以这样
Weixin weixin2 = new Build("","",0).setName("sss").setAge(26).setPswdString("5656").build();
}
}
1.明白建造者是怎么一种设计模式
2.利用链式编程可以简化代码,给属性赋值或者改变值