软件设计 石家庄铁道大学信息学院
实验5:建造者模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解建造者模式的动机,掌握该模式的结构;
2、能够利用建造者模式解决实际问题。
[实验任务一]:计算机组装
使用建造者模式,完成下述任务:计算机组装工厂可以将CPU、内存、硬盘、主机等硬件设备组装在一起构成计算机,计算机的类型可以是笔记本,也可以是台式机。
实验要求:
1.画出对应的类图;
2.提交源代码;
3.注意编程规范。
1.Computer.java
package org.example;
public class Computer {
private String CPU;
private String RAM;
private String Dist;
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 getDist() {
return Dist;
}
public void setDist(String dist) {
Dist = dist;
}
public String getHost() {
return Host;
}
public void setHost(String host) {
Host = host;
}
}
2.ComputerBuilder.java
package org.example;
public abstract class ComputerBuilder {
protected Computer computer = new Computer();
public abstract void buildCPU();
public abstract void buildRAM();
public abstract void buildDist();
public abstract void buildHost();
public Computer getComputer() {
return computer;
}
}
3.DesktopBuilder.java
package org.example;
public class DesktopBuilder extends ComputerBuilder{
public void buildCPU() {
computer.setCPU("已经安装台式机的CPU");
}
public void buildRAM() {
computer.setRAM("已经安装台式机的内存");
}
public void buildDist() {
computer.setDist("已经安装台式机的硬盘");
}
public void buildHost() {
computer.setHost("已经安装台式机的主机");
}
}
4.Director.java
package org.example;
public class Director {
private ComputerBuilder builder;
public void setComputerBuilder(ComputerBuilder c)
{
builder=c;
}
public Computer construct()
{
builder.buildCPU();
builder.buildRAM();
builder.buildDist();
builder.buildHost();
return builder.getComputer();
}
}
5.LaptopBuilder.java
package org.example;
public class LaptopBuilder extends ComputerBuilder{
public void buildCPU() {
computer.setCPU("已经安装笔记本的CPU");
}
public void buildRAM() {
computer.setRAM("已经安装笔记本的内存");
}
public void buildDist() {
computer.setDist("已经安装笔记本的硬盘");
}
public void buildHost() {
computer.setHost("已经安装笔记本的主机");
}
}