[实验任务一]:计算机组装
使用建造者模式,完成下述任务:计算机组装工厂可以将CPU、内存、硬盘、主机等硬件设备组装在一起构成计算机,计算机的类型可以是笔记本,也可以是台式机。
实验要求:
-
画出对应的类图;
-
提交源代码;
// Computer.java
package builder;public class Computer {private String cpu; // CPUprivate String memory; // 内存private String hardDisk; // 硬盘private String computerCase; // 机箱public void setCpu(String cpu) {this.cpu = cpu;}public void setMemory(String memory) {this.memory = memory;}public void setHardDisk(String hardDisk) {this.hardDisk = hardDisk;}public void setCase(String computerCase) {this.computerCase = computerCase;}public void display() {System.out.println("电脑配置信息:");System.out.println("处理器: " + cpu);System.out.println("内存: " + memory);System.out.println("硬盘: " + hardDisk);System.out.println("机箱: " + computerCase);}
}// ComputerBuilder.java
package builder;public abstract class ComputerBuilder {protected Computer computer = new Computer();public abstract void buildCpu();public abstract void buildMemory();public abstract void buildHardDisk();public abstract void buildCase();public Computer getResult() {return computer;}
}// LaptopBuilder.java
package builder;public class LaptopBuilder extends ComputerBuilder {@Overridepublic void buildCpu() {computer.setCpu("笔记本处理器:Intel Core i7 移动版");}@Overridepublic void buildMemory() {computer.setMemory("笔记本内存:16GB LPDDR4");}@Overridepublic void buildHardDisk() {computer.setHardDisk("笔记本硬盘:512GB NVMe固态硬盘");}@Overridepublic void buildCase() {computer.setCase("笔记本机箱:轻薄铝合金机身");}
}// DesktopBuilder.java
package builder;public class DesktopBuilder extends ComputerBuilder {@Overridepublic void buildCpu() {computer.setCpu("台式机处理器:Intel Core i9");}@Overridepublic void buildMemory() {computer.setMemory("台式机内存:32GB DDR4");}@Overridepublic void buildHardDisk() {computer.setHardDisk("台式机硬盘:2TB机械硬盘 + 1TB固态硬盘");}@Overridepublic void buildCase() {computer.setCase("台式机机箱:ATX立式机箱");}
}// Director.java
package builder;public class Director {private ComputerBuilder builder;public void setBuilder(ComputerBuilder builder) {this.builder = builder;}public Computer construct() {builder.buildCpu();builder.buildMemory();builder.buildHardDisk();builder.buildCase();return builder.getResult();}
}// Main.java
package builder;public class Main {public static void main(String[] args) {Director director = new Director();// 构建笔记本电脑LaptopBuilder laptopBuilder = new LaptopBuilder();director.setBuilder(laptopBuilder);Computer laptop = director.construct();System.out.println("=== 笔记本电脑配置 ===");laptop.display();System.out.println("\n");// 构建台式机DesktopBuilder desktopBuilder = new DesktopBuilder();director.setBuilder(desktopBuilder);Computer desktop = director.construct();System.out.println("=== 台式机配置 ===");desktop.display();}
}
3.注意编程规范。