画类图
具体代码实现
//Computer.java
package org.example.design003;
public class Computer {
public Computer(String CPU, String RAM, String hard, String host) {
this.CPU = CPU;
this.RAM = RAM;
Hard = hard;
Host = host;
}
public Computer(){}
public String getCPU() {
return CPU;
}
public void setCPU(String CPU) {
this.CPU = CPU;
}
public String getRAM() {
return RAM;
}
public void setRAM(String RAM) {
this.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;
}
private String CPU;
private String RAM;
private String Hard;
private String Host;
}
//ComputerBuilder.java
package org.example.design003;
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;
}
}
//DesktopComputerBuilder.java
package org.example.design003;
public class DesktopComputerBuilder extends ComputerBuilder{
@Override
public void buildCPU() {
computer.setCPU("安装台式机CPU");
}
@Override
public void buildRAM() {
computer.setRAM("安装台式机内存");
}
@Override
public void buildHard() {
computer.setHard("安装台式机硬盘");
}
@Override
public void buildHost() {
computer.setHost("安装台式机主机");
}
}
//LaptopComputerBuilder.java
package org.example.design003;
public class LaptopComputerBuilder extends ComputerBuilder {
@Override
public void buildCPU() {
computer.setCPU("安装笔记本CPU");
}
@Override
public void buildRAM() {
computer.setRAM("安装笔记本内存");
}
@Override
public void buildHard() {
computer.setHard("安装笔记本硬盘");
}
@Override
public void buildHost() {
computer.setHost("安装笔记本主机");
}
}
//Director.java
package org.example.design003;
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();
}
}
//Main.java
package org.example.design003;
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());
}
}