标签:builder String void 建造 模式 computer Override public
实验5:建造者模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解建造者模式的动机,掌握该模式的结构;
2、能够利用建造者模式解决实际问题。
[实验任务一]:计算机组装
使用建造者模式,完成下述任务:计算机组装工厂可以将CPU、内存、硬盘、主机等硬件设备组装在一起构成计算机,计算机的类型可以是笔记本,也可以是台式机。
实验要求:
1. 画出对应的类图;
2.提交源代码;
// 计算机类
class Computer {
private String cpu;
private String ram;
private String hardDrive;
private String caseType;
public void setCpu(String cpu) {
this.cpu = cpu;
}
public void setRam(String ram) {
this.ram = ram;
}
public void setHardDrive(String hardDrive) {
this.hardDrive = hardDrive;
}
public void setCaseType(String caseType) {
this.caseType = caseType;
}
@Override
public String toString() {
return "Computer [CPU=" + cpu + ", RAM=" + ram + ", Hard Drive=" + hardDrive + ", Case Type=" + caseType + "]";
}
}
// 抽象建造者类
abstract class Builder {
protected Computer computer;
public void createNewComputer() {
computer = new Computer();
}
public Computer getComputer() {
return computer;
}
public abstract void buildCPU();
public abstract void buildRAM();
public abstract void buildHardDrive();
public abstract void buildCaseType();
}
// 笔记本建造者类
class LaptopBuilder extends Builder {
@Override
public void buildCPU() {
computer.setCpu("Intel i5");
}
@Override
public void buildRAM() {
computer.setRam("8GB");
}
@Override
public void buildHardDrive() {
computer.setHardDrive("512GB SSD");
}
@Override
public void buildCaseType() {
computer.setCaseType("Ultrabook");
}
}
// 台式机建造者类
class DesktopBuilder extends Builder {
@Override
public void buildCPU() {
computer.setCpu("AMD Ryzen 5");
}
@Override
public void buildRAM() {
computer.setRam("16GB");
}
@Override
public void buildHardDrive() {
computer.setHardDrive("1TB HDD");
}
@Override
public void buildCaseType() {
computer.setCaseType("Tower");
}
}
// 指导者类
class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public Computer constructComputer() {
builder.createNewComputer();
builder.buildCPU();
builder.buildRAM();
builder.buildHardDrive();
builder.buildCaseType();
return builder.getComputer();
}
}
// 测试类
public class Main {
public static void main(String[] args) {
// 建造笔记本电脑
Builder laptopBuilder = new LaptopBuilder();
Director laptopDirector = new Director(laptopBuilder);
Computer laptop = laptopDirector.constructComputer();
System.out.println(laptop);
// 建造台式机
Builder desktopBuilder = new DesktopBuilder();
Director desktopDirector = new Director(desktopBuilder);
Computer desktop = desktopDirector.constructComputer();
System.out.println(desktop);
}
}
标签:builder,
String,
void,
建造,
模式,
computer,
Override,
public
From: https://www.cnblogs.com/Christmas77/p/18642599