设计模式练习(10)——外观模式

来源:互联网 发布:朗读语文课文软件 编辑:程序博客网 时间:2024/06/07 05:08

外观模式

一、题目:

在计算机主机(MainFrame)中,只需要按下主机的开机按钮(on()),就可以调用其他硬件设备和软件的启动方法,如内存(Memory)的自检(check()),CPU的运行(run()),硬盘(Harddisk)的读取(read()),操作系统(OS)的载入(load())等,如果某一过程发生错误,则计算机启动失败,使用外观模式模拟该过程绘制类图并编程实现。
(1)实现给出外观模式结构视图。
(2)给出该实例类图及代码实现。

二、所用模式结构视图:

这里写图片描述

三、实例类图:

这里写图片描述

四、实例实现代码:

(因为区分,所以在类的前面加了Gj19)

主窗口类:外观类

package FacadePattern;/** * 主窗口类:外观类 * @author gong * */public class Gj19Mainframe {    private Gj19Memory gj19memory;    private Gj19CPU gj19cpu;    private Gj19HardDisk gj19disk;    private Gj19OS gj19os;    public Gj19Mainframe() {        gj19memory = new Gj19Memory();        gj19cpu = new Gj19CPU();        gj19disk = new Gj19HardDisk();        gj19os = new Gj19OS();    }    public void on(){        gj19memory.check();        gj19cpu.run();        gj19disk.read();        gj19os.load();    }    public void off(){        gj19memory.off();        gj19cpu.off();        gj19disk.off();        gj19os.off();    }}

Memory类:子系统类

package FacadePattern;/** * Memory类:子系统类 * @author gong * */public class Gj19Memory {    public void check(){        System.out.println("Memory is checking.....");    }    public void off(){        System.out.println("Memory off.....");    }}

CPU类:子系统类

package FacadePattern;/** * CPU类:子系统类 * @author gong * */public class Gj19CPU {    public void run(){        System.out.println("CPU is running.....");    }    public void off(){        System.out.println("CPU off.....");    }}

HardDisk(硬盘)类:子系统类

package FacadePattern;/** * HardDisk(硬盘)类:子系统类 * @author gong * */public class Gj19HardDisk {    public void read(){        System.out.println("HardDisk is reading.....");    }    public void off(){        System.out.println("HardDisk off.....");    }}

操作系统OS类:子系统类

package FacadePattern;/** * 操作系统OS类:子系统类 * @author gong * */public class Gj19OS {    public void load(){        System.out.println("OS is loading.....");    }    public void off(){        System.out.println("OS off.....");    }}

外观模式客户端测试类

package FacadePattern;/** * 外观模式客户端测试类 * @author gong * */public class Gj19Client {    public static void main(String[] args) {        Gj19Mainframe gj19Mainframe = new Gj19Mainframe();        System.out.println("电脑开机....");        gj19Mainframe.on();        System.out.println("电脑关闭....");        gj19Mainframe.off();    }}

五、运行结果:

这里写图片描述

0 0
原创粉丝点击