建造者模式——java实现
使用建造者模式,完成下述任务:计算机组装工厂可以将CPU、内存、硬盘、主机等硬件设备组装在一起构成计算机,计算机的类型可以是笔记本,也可以是台式机。
类图:
java代码:
//Computer.java package shiyan5; 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; } } //ComputerBuilder.java package shiyan5; 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 shiyan5; 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("安装台式机主机"); } } //LaptopComputerBuilder.java package shiyan5; 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("安装笔记本主机"); } } //Director.java package shiyan5; 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 shiyan5; 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()); } }