软件设计 石家庄铁道大学信息学院
实验5:建造者模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解建造者模式的动机,掌握该模式的结构;
2、能够利用建造者模式解决实际问题。
[实验任务一]:计算机组装
使用建造者模式,完成下述任务:计算机组装工厂可以将CPU、内存、硬盘、主机等硬件设备组装在一起构成计算机,计算机的类型可以是笔记本,也可以是台式机。
实验要求:
1. 画出对应的类图;
![](https://img2023.cnblogs.com/blog/2913877/202312/2913877-20231228115040988-722193774.png)
2. 提交源代码;
package Builder;
public class Computer {
private String CPU;
private String RAM;
private String Hard;
private String Host;
public String getCPU() {
return CPU;
}
public void setCPU(String cPU) {
CPU = cPU;
}
public String getRAM() {
return RAM;
}
public void setRAM(String rAM) {
RAM = rAM;
}
public String getHard() {
return Hard;
}
public void setHard(String hard) {
Hard = hard;
}
public String getHost() {
return Host;
}
public void setHost(String host) {
Host = host;
}
}
package Builder;
public abstract class ComputerBuilder {
protected Computer computer=new Computer();
public abstract void buildCPU();
public abstract void buildRAM();
public abstract void buildHard();
public abstract void buildHost();
public Computer getComputer()
{
return computer;
}
}
package Builder;
public class DesktopComputerBuilder extends ComputerBuilder{
public void buildCPU() {
computer.setCPU("安装台式机CPU");
}
public void buildRAM() {
computer.setRAM("安装台式机内存");
}
public void buildHard() {
computer.setHard("安装台式机硬盘");
}
public void buildHost() {
computer.setHost("安装台式机主机");
}
}
package Builder;
public class Director {
private ComputerBuilder cb;
public void setComputerBuilder(ComputerBuilder c)
{
cb=c;
}
public Computer construct()
{
cb.buildCPU();
cb.buildRAM();
cb.buildHard();
cb.buildHost();
return cb.getComputer();
}
}
package Builder;
public class LaptopComputerBuilder extends ComputerBuilder{
public void buildCPU() {
computer.setCPU("安装笔记本CPU");
}
public void buildRAM() {
computer.setRAM("安装笔记本内存");
}
public void buildHard() {
computer.setHard("安装笔记本硬盘");
}
public void buildHost() {
computer.setHost("安装笔记本主机");
}
}
package Builder;
import java.util.Scanner;
public class main {
public static void main(String args[])
{
ComputerBuilder cb = null;
System.out.println("请选择:1、笔记本 2、台式机");
Scanner input=new Scanner(System.in);
int i=input.nextInt();
if(i==1) {
cb=new LaptopComputerBuilder();
}else if(i==2) {
cb=new DesktopComputerBuilder();
}else {
System.out.println("输入无效!");
}
Director dir=new Director();
dir.setComputerBuilder(cb);
Computer computer=dir.construct();
System.out.println("计算机组成:");
System.out.println(computer.getCPU());
System.out.println(computer.getRAM());
System.out.println(computer.getHard());
System.out.println(computer.getHost());
}
}
//run此文件
3.注意编程规范。