每日随笔——外观模式
实验任务一]:计算机开启
在计算机主机(Mainframe)中,只需要按下主机的开机按钮(on()),即可调用其他硬件设备和软件的启动方法 ,如内存(Memory)的自检(check())、CPU的运行(run())、硬盘(HardDisk)的读取(read())、操作系统(OS)的载入(load()),如果某一过程发生错误则计算机启动失败。
实验要求:
1.提交类图;
2.提交源代码;
3.注意编程规范。
源码:
Client package SC12; public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Mainframe mainframe = new Mainframe(); mainframe.on(); } } Mainframe package SC12; public class Mainframe { private Memory memory; private CPU cpu; private HardDisk hardDisk; private OS os; private boolean operIf = true; public void setOperIf(boolean operIf) { this.operIf = operIf; } public Mainframe() { super(); this.memory = memory.getInstance(); this.cpu = cpu.getInstance(); this.hardDisk = hardDisk.getInstance(); this.os = os.getInstance(); } public void on() { System.out.println("按下主机按钮"); operIf=memory.check(operIf); operIf=cpu.run(operIf); operIf=hardDisk.read(operIf); operIf=os.load(operIf); } } Memory package SC12; public class Memory { private static Memory instance = new Memory(); public static Memory getInstance() { return instance; } public boolean check(boolean operIf) { System.out.println("内存开始自检"); if (operIf) { operIf = new java.util.Random().nextBoolean() ? true : false; } if (operIf) { System.out.println("内存自检完成"); return true; } else { System.out.println("内存自检失败"); return false; } } } CPU package SC12; public class CPU { private static CPU instance = new CPU(); public static CPU getInstance() { return instance; } public boolean run(boolean operIf) { System.out.println("cpu开始运行"); if (operIf) { operIf =new java.util.Random().nextBoolean() ? true : false; } if (operIf) { System.out.println("cpu运行成功"); return true; } else { System.out.println("cpu运行失败"); return false; } } } HardDisk package SC12; public class HardDisk { private static HardDisk instance = new HardDisk(); public static HardDisk getInstance() { return instance; } public boolean read(boolean operIf) { System.out.println("硬盘开始读取"); if (operIf) { operIf =new java.util.Random().nextBoolean() ? true : false; } if (operIf) { System.out.println("硬盘运行成功"); return true; } else { System.out.println("硬盘运行失败"); return false; } } } OS package SC12; public class OS { private static OS instance = new OS(); public static OS getInstance() { return instance; } public boolean load(boolean operIf) { System.out.println("操作系统开始载入"); if (operIf) { operIf =new java.util.Random().nextBoolean() ? true : false; } if (operIf) { System.out.println("操作系统载入成功"); return true; } else { System.out.println("操作系统载入失败"); return false; } } }