构建者模式常规写法
背景
当构建一个对象,参数超过了4个;或者构建对象,属性设置有先后顺序或依赖关系等场景,可以选择使用构建者模式
常规写法
/**
* @Description 构造器模式
* @Date 2021/7/22 10:49 PM
* @Created by dwb
* 微信: snail_java
*/
public class Computer {
/**
* 主板 这些属性 不需要设置 set 方法;如果需要对外提供属性,可设置get方法
*/
private String mainBoard;
/**
* cpu
*/
private String cpu;
/**
* 内存
*/
private String ram;
/**
* 显示器
*/
private String monitor;
/**
* 键盘
*/
private String keyboard;
/**
* 鼠标
*/
private String mouse;
public static class Builder {
private String mainBoard;
private String cpu;
private String ram;
private String monitor;
private String keyboard;
private String mouse;
/**
* 必须有主板才能谈得上组装电脑;所以主板是Build构造必须条件
*
* @param mainBoard 鼠标
*/
public Builder(String mainBoard) {
this.mainBoard = mainBoard;
}
public Builder cpu(String cpu) {
this.cpu = cpu;
return this;
}
public Builder ram(String ram) {
this.ram = ram;
return this;
}
public Builder monitor(String monitor) {
this.monitor = monitor;
return this;
}
public Builder keyboard(String keyboard) {
this.keyboard = keyboard;
return this;
}
public Builder mouse(String mouse) {
this.mouse = mouse;
return this;
}
/**
* 前面是组装过程;这一步才是 交付给用户的 电脑;用户可以使用该电脑
*
* @return 返回电脑实例
*/
public Computer build() {
return new Computer(this);
}
}
/**
* 注意 权限是 private;这样创建实例就交给了 Builder
*
* @param builder 构建者(组装电脑的人)
*/
private Computer(Builder builder) {
this.mainBoard = builder.mainBoard;
this.cpu = builder.cpu;
this.ram = builder.ram;
this.monitor = builder.monitor;
this.keyboard = builder.keyboard;
this.mouse = builder.mouse;
}
public void start() {
System.out.println(mainBoard + " 启动;\n"
+ ram + " 读取程序;\n"
+ cpu + " 调度程序;\n"
+ monitor + " 显示图像;\n"
+ keyboard + " 打字;\n"
+ mouse + " 控制光标");
}
public static void main(String[] args) {
Computer computer = new Builder("华硕主板")
.cpu("i5处理器").ram("金士顿内存")
.monitor("小米显示器").keyboard("罗技键盘").mouse("雷蛇鼠标")
.build();
computer.start();
}
}
网友评论