设计模式-外观模式
[实验任务一]:计算机开启
在计算机主机(Mainframe)中,只需要按下主机的开机按钮(on()),即可调用其他硬件设备和软件的启动方法 ,如内存(Memory)的自检(check())、CPU的运行(run())、硬盘(HardDisk)的读取(read())、操作系统(OS)的载入(load()),如果某一过程发生错误则计算机启动失败。
Java代码
package t12; import java.util.Scanner; public class Client { public static void main(String[] args) { // TODO 自动生成的方法存根 while (true) { MainFrame f = new MainFrame(); Scanner scan = new Scanner(System.in); System.out.println("请输入ON进行开机:"); String str = scan.nextLine(); if (str.equals("ON")) { f.fun(); } else { System.out.println("输入的信息有误!!!请重新输入"); } } } } package t12; public class Cpu { public void display() { System.out.println("cpu运行正常"); } } package t12; public class HardDisk { public void display() { System.out.println("硬盘读取正常"); } } package t12; public class MainFrame { private Memory memory = new Memory(); // 关联关系建立联系 private Cpu cpu = new Cpu(); private HardDisk harddisk = new HardDisk(); private Os os = new Os(); public void fun() { memory.display(); cpu.display(); harddisk.display(); os.display(); System.out.println("开机正常"); } } package t12; public class Memory { public void display() { System.out.println("内存正常"); } } package t12; public class Os { public void display() { System.out.println("操作系统载入正常"); } }
c++代码
#include<iostream> using namespace std; class Sub_Work1//子工作1 { public: void check() { cout<<"Memory START OK"<<endl; } }; class Sub_Work2//子工作2 { public: void run() { cout<<"CPU START OK"<<endl; } }; class Sub_Work3//子工作3 { public: void read() { cout<<"HardDisk START OK"<<endl; } }; class Sub_Work4//子工作4 { public: void load() { cout<<"OS START OK"<<endl; } }; class Work { private: Sub_Work1 w1; Sub_Work2 w2; Sub_Work3 w3; Sub_Work4 w4; public: void Work1() { w1.check(); w2.run(); w3.read(); w4.load(); } }; main() { string o; cout<<"输入ON开机"<<endl; cin>>o; if(o=="ON"||o=="on") { Work w; w.Work1(); } else cout<<"ERROR!"<<endl; }