每日随笔——建造者模式
[实验任务一]:计算机组装
使用建造者模式,完成下述任务:计算机组装工厂可以将CPU、内存、硬盘、主机等硬件设备组装在一起构成计算机,计算机的类型可以是笔记本,也可以是台式机。
实验要求:
1.画出对应的类图;
2.提交源代码;
3.注意编程规范。
1、类图
2、源码
Builder
package sc5; public abstract class Builder { Computer computer = new Computer(); abstract public void buildZhuJi(); abstract public void buildYinPan(); abstract public void buildCpu(); abstract public void buildNeiCun(); public Computer getCompture(){ return computer; } } computer
package sc5; public class Computer { private String cpu; private String neiCun; private String yinPan; private String zhuJi; public String getZhuJi() { return zhuJi; } public void setZhuJi(String zhuJi) { this.zhuJi = zhuJi; } public String getYinPan() { return yinPan; } public void setYinPan(String yinPan) { this.yinPan = yinPan; } public String getNeiCun() { return neiCun; } public void setNeiCun(String neiCun) { this.neiCun = neiCun; } public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } } desktop
package sc5; public class desktop extends Builder{ @Override public void buildZhuJi() { computer.setZhuJi("DZJ"); } @Override public void buildYinPan() { computer.setYinPan("DYP"); } @Override public void buildCpu() { computer.setCpu("DCPU"); } @Override public void buildNeiCun() { computer.setNeiCun("DNC"); } } Factory
package sc5; public class Factory { private Builder comptureKind; public void setCompture(Builder kind) { this.comptureKind = kind; } public Computer construct(){ comptureKind.buildCpu(); comptureKind.buildYinPan(); comptureKind.buildZhuJi(); comptureKind.buildNeiCun(); return comptureKind.getCompture(); } } mobile
package sc5; public class mobile extends Builder{ @Override public void buildZhuJi() { computer.setZhuJi("MZJ"); } @Override public void buildYinPan() { computer.setYinPan("MYP"); } @Override public void buildCpu() { computer.setCpu("MCPU"); } @Override public void buildNeiCun() { computer.setNeiCun("MNC"); } } Store
package sc5; public class Store { public static void main(String[] args) { Builder lap; Factory factory=new Factory(); for (int i = 0; i < 2; i++) { if(i==1) lap = new mobile(); else lap=new desktop(); factory.setCompture(lap); factory.construct(); System.out.println(lap.getCompture().getCpu()); System.out.println(lap.getCompture().getNeiCun()); System.out.println(lap.getCompture().getYinPan()); System.out.println(lap.getCompture().getZhuJi()); } } }