10.3

软件设计                  石家庄铁道大学信息学院

 

实验12:外观模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解外观模式的动机,掌握该模式的结构;

2、能够利用外观模式解决实际问题。

 
   

 


[实验任务一]:计算机开启

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

实验要求:

1.  提交类图;

 

 

2.提交源代码;

// 内存接口

interface Memory {

    void check();

}

 

// 内存实现类

class MemoryImpl implements Memory {

    @Override

    public void check() {

        System.out.println("正在进行内存自检...");

        // 模拟内存自检失败的情况

        if (Math.random() < 0.2) {

            throw new RuntimeException("内存自检出现问题");

        }

        System.out.println("内存自检完成,无异常");

    }

}

 

 

// CPU接口

interface CPU {

    void run();

}

 

// CPU实现类

class CPUImpl implements CPU {

    @Override

    public void run() {

        System.out.println("CPU开始运行...");

        // 模拟CPU运行失败的情况

        if (Math.random() < 0.1) {

            throw new RuntimeException("CPU运行出现问题");

        }

        System.out.println("CPU运行正常");

    }

}

 

 

 

// 硬盘接口

interface HardDisk {

    void read();

}

 

// 硬盘实现类

class HardDiskImpl implements HardDisk {

    @Override

    public void read() {

        System.out.println("正在读取硬盘数据...");

        // 模拟硬盘读取失败的情况

        if (Math.random() < 0.3) {

            throw new RuntimeException("硬盘读取出现问题");

        }

        System.out.println("硬盘数据读取成功");

    }

}

 

 

 

 

// 操作系统接口

interface OperatingSystem {

    void load();

}

 

// 操作系统实现类

class OperatingSystemImpl implements OperatingSystem {

    @Override

    public void load() {

        System.out.println("正在载入操作系统...");

        // 模拟操作系统载入失败的情况

        if (Math.random() < 0.15) {

            throw new RuntimeException("操作系统载入出现问题");

        }

        System.out.println("操作系统载入成功");

    }

}

 

 

 

 

// 外观类

class ComputerFacade {

    private Memory memory;

    private CPU cpu;

    private HardDisk hardDisk;

    private OperatingSystem operatingSystem;

 

    public ComputerFacade() {

        this.memory = new MemoryImpl();

        this.cpu = new CPUImpl();

        this.hardDisk = new HardDiskImpl();

        this.operatingSystem = new OperatingSystemImpl();

    }

 

    public void turnOnComputer() {

        try {

            memory.check();

            cpu.run();

            hardDisk.read();

            operatingSystem.load();

            System.out.println("计算机启动成功!");

        } catch (Exception e) {

            System.out.println("计算机启动失败,原因:" + e.getMessage());

        }

    }

}

 

 

 

public class Main {

    public static void main(String[] args) {

        ComputerFacade computerFacade = new ComputerFacade();

        computerFacade.turnOnComputer();

    }

}

3.注意编程规范。

 

 

posted @ 2025-01-02 15:28  jais  阅读(14)  评论(0)    收藏  举报