Builder模式是一种一步一步创建一个复杂对象的设计模式,我认为这种设计模式的精髓就主要有两点:其一,用户使用简单,并且可以在不需要知道内部构建细节的情况下,就可以构建出复杂的对象模型;其二,对于设计者来说,这是一个解耦的过程,这种设计模式可以将构建的过程和具体的表示分离开来。
package BuilderPattern;
public class Student {
private int stuNum ;
private String name ;
private int age ;
private String address ;
private boolean girlfriend ;
private Student(){}//定义私有构造器,只能在类内部使用(提供给静态内部类创建一个对象)
// 定义私有的有参构造器 ,即给对象的属性赋值,由静态内部类调用
private Student(int stuNum,String name,int age,String address,boolean girlfriend){
this.stuNum = stuNum ;
this.name = name ;
this.age = age ;
this.address = address ;
this.girlfriend = girlfriend ;
}
public int getStuNum() {
return stuNum;
}
public void setStuNum(int stuNum) {
this.stuNum = stuNum;
}
public StringgetName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public StringgetAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isGirlfriend() {
return girlfriend;
}
public void setGirlfriend(boolean girlfriend) {
this.girlfriend = girlfriend;
}
public static class Builder{//静态内部类,通过该类来创建一个外部类对象,使用链式调用
private Studentstudent ;//创建一个外部类对象
//构造一个内部类对象,通过该对象设置属性值
//如果存在必填参数,可以以带参构造函数的方式传过来
public Builder(int stuNum,String name,int age,String address,boolean girlfriend){
student =new Student(stuNum,name,age,address,girlfriend);
}
public Builder(){
student =new Student();
}
public Builder stuNum(int stuNum){
student.stuNum = stuNum;
return this ;
}
public Builder name(String name){
student.name = name;
return this ;
}
public Builder age(int age){
student.age = age;
return this ;
}
public Builder address(String address){
student.address = address;
return this ;
}
public Builder girlfriend(boolean girlfriend){
student.girlfriend = girlfriend;
return this ;
}
public Student build(){
return student;
}
}
}
调用:
// 第一种方式
Student student1 =new Student.Builder(1,"老王",36,"隔壁",false)
.build();
//第二种方式
Student student2 =new Student.Builder()
.stuNum(2)
.name("小张")
.age(20)
.address("上海")
.girlfriend(true)
.build();
System.out.println(student1.toString() +" \n" + student2.toString());
输出: 我重写了toString()
stuNo:1,name:老王,age:36,address:隔壁,grilfriend:false
stuNo:2,name:小张,age:20,address:上海,grilfriend:true