[實驗任務一]:計算機組裝
使用建造者模式,完成下述任務:計算機組裝工廠可以將CPU、記憶體、硬碟、主機等硬體裝置組裝在一起構成計算機,計算機的型別可以是筆記本,也可以是桌上型電腦。
package test5; 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 test5; 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 test5; 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 test5; 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 test5; 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 test5; 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此檔案