软件设计-外观模式

计算机开启
在计算机主机(Mainframe)中,只需要按下主机的开机按钮(on()),即可调用其他硬件设备和软件的启动方法 ,如内存(Memory)的自检(check())、CPU的运行(run())、硬盘(HardDisk)的读取(read())、操作系统(OS)的载入(load()),如果某一过程发生错误则计算机启动失败。

 

类图

 

 

java

package rjsj.no12;

/**
 * CPU类:子系统类
 *
 */
public class CPU {
    public void run(){
        System.out.println("处理器运行");
    }
    public void off(){
        System.out.println("处理器关闭");
    }
}
package rjsj.no12;

/**
 * Disk(硬盘)类:子系统类
 *
 */
public class Disk {
    public void read(){
        System.out.println("硬盘读取");
    }
    public void off(){
        System.out.println("硬盘关闭");
    }
}
package rjsj.no12;

/**
 * Memory类:子系统类
 *
 */
public class Memory {
    public void check(){
        System.out.println("内存自检");
    }
    public void off(){
        System.out.println("内存关闭");
    }
}
package rjsj.no12;

/**
 * 操作系统OS类:子系统类
 *
 */
public class OS {
    public void load(){
        System.out.println("操作系统载入");
    }
    public void off(){
        System.out.println("操作系统关闭");
    }
}
package rjsj.no12;

/**
 * 主窗口类:外观类
 *
 */
public class Mainframe {
    private Memory memory;
    private CPU cpu;
    private Disk disk;
    private OS os;

    public Mainframe(){
        memory = new Memory();
        cpu = new CPU();
        disk = new Disk();
        os = new OS();
    }

    public void on(){
        memory.check();
        cpu.run();
        disk.read();
        os.load();
    }

    public void off(){
        memory.off();
        cpu.off();
        disk.off();
        os.off();
    }
}
package rjsj.no12;

public class Client {
    public static void main(String[] args) {
        Mainframe mainframe = new Mainframe();
        System.out.println("电脑启动中...");
        mainframe.on();
        System.out.println("启动完成。");
        System.out.println("电脑关闭中...");
        mainframe.off();
        System.out.println("关闭完成。");
    }
}

 

C++

#include <iostream>

using namespace std;

class Memory{
public:
    void check(){
        cout<<"内存自检"<<endl;
    }
    void off(){
        cout<<"内存关闭"<<endl;
    }
};

class Cpu{
public:
    void run(){
        cout<<"CPU运行"<<endl;
    }
    void off(){
        cout<<"CPU关闭"<<endl;
    }
};

class HardDisk{
public:
    void read(){
        cout<<"硬盘读取"<<endl;
    }
    void off(){
        cout<<"硬盘关闭"<<endl;
    }
};

class Os{
public:
    void load(){
        cout<<"操作系统加载"<<endl;
    }
    void off(){
        cout<<"操作系统关闭"<<endl;
    }
};

class MainFrame{
private:
    Memory w1;
    Cpu w2;
    HardDisk w3;
    Os w4;
public:
    void on(){
        cout<<"开机中......"<<endl;
        w1.check();
        w2.run();
        w3.read();
        w4.load();
    }
    void off(){
        cout<<"关机中......"<<endl;
        w1.off();
        w2.off();
        w3.off();
        w4.off();
    }
};


int main(){
    MainFrame w;
    w.on();
    w.off();
    return 0;
}

 

运行截图

 

posted @ 2021-12-13 22:32  Arisf  阅读(302)  评论(0编辑  收藏  举报