外观模式——Java实现
问题描述:
在计算机主机(Mainframe)中,只需要按下主机的开机按钮(on()),即可调用其他硬件设备和软件的启动方法 ,如内存(Memory)的自检(check())、CPU的运行(run())、硬盘(HardDisk)的读取(read())、操作系统(OS)的载入(load()),如果某一过程发生错误则计算机启动失败。
类图:
代码:
//MainFrame.java package shiyan12; public class MainFrame { private Memory memory; private CPU cpu; private HardDisk hd; private OS os; public MainFrame(){ memory=new Memory(); cpu=new CPU(); hd=new HardDisk(); os=new OS(); } public void start(){ if(memory.check()&&cpu.run()&&hd.read()&&os.load()){ System.out.println("*****电脑启动成功*****"); return ; } System.out.println("电脑启动失败"); } } //CPU.java package shiyan12; public class CPU { public boolean run(){ System.out.println("CPU自动成功"); return true; } } //HardDisk.java package shiyan12; public class HardDisk { public boolean read(){ System.out.println("硬盘读入成功"); return true; } } //Memory.java package shiyan12; public class Memory { public boolean check(){ System.out.println("内存检查成功"); return true; } } //OS.java package shiyan12; public class OS { public boolean load(){ System.out.println("操作系统载入成功"); return true; } }
运行结果: