11.14日学习笔记

类图设计
text
+------------------------+
| Computer |
+------------------------+
| -memory: Memory |
| -cpu: CPU |
| -hardDisk: HardDisk |
| -os: OS |
+------------------------+
| +powerOn(): boolean |
| +powerOff(): boolean |
| +getStatus(): String |
+------------------------+
|
| 使用
|
+------------------------+
| Mainframe |
+------------------------+
| -computer: Computer |
+------------------------+
| +on(): boolean |
| +off(): boolean |
| +getSystemInfo(): String|
+------------------------+

|
+------------------------+
| Client |
+------------------------+

+------------------------+ +------------------------+
| Memory | | CPU |
+------------------------+ +------------------------+
| +check(): boolean | | +run(): boolean |
| +getSize(): long | | +getFrequency(): double|
| +getStatus(): String | | +getStatus(): String |
+------------------------+ +------------------------+

+------------------------+ +------------------------+
| HardDisk | | OS |
+------------------------+ +------------------------+
| +read(): boolean | | +load(): boolean |
| +write(): boolean | | +shutdown(): boolean |
| +getCapacity(): long | | +getVersion(): String |
| +getStatus(): String | | +getStatus(): String |
+------------------------+ +------------------------+
Java源代码实现

  1. 子系统类 - 内存
    java
    // Memory.java - 内存子系统
    public class Memory {
    private long size; // 内存大小(MB)
    private boolean isChecked;

    public Memory(long size) {
    this.size = size;
    this.isChecked = false;
    }

    /**

    • 内存自检
      */
      public boolean check() {
      System.out.println("🔄 内存自检中...");
      try {
      // 模拟自检过程
      Thread.sleep(1000);

       // 模拟自检结果(90%概率成功)
       boolean success = Math.random() > 0.1;
       
       if (success) {
           System.out.println("✅ 内存自检通过");
           isChecked = true;
           return true;
       } else {
           System.out.println("❌ 内存自检失败:发现错误");
           return false;
       }
      

      } catch (InterruptedException e) {
      System.out.println("❌ 内存自检过程被中断");
      return false;
      }
      }

    /**

    • 获取内存大小
      */
      public long getSize() {
      return size;
      }

    /**

    • 获取内存状态
      */
      public String getStatus() {
      if (!isChecked) {
      return "未自检";
      }
      return "正常运行 - " + (size / 1024) + " GB";
      }

    /**

    • 清理内存状态
      */
      public void reset() {
      isChecked = false;
      System.out.println("🧹 内存状态已重置");
      }
      }
  2. 子系统类 - CPU
    java
    // CPU.java - CPU子系统
    public class CPU {
    private String model;
    private double frequency; // GHz
    private boolean isRunning;

    public CPU(String model, double frequency) {
    this.model = model;
    this.frequency = frequency;
    this.isRunning = false;
    }

    /**

    • 启动CPU运行
      */
      public boolean run() {
      System.out.println("🚀 启动CPU运行...");
      try {
      // 模拟启动过程
      Thread.sleep(800);

       // 模拟启动结果(95%概率成功)
       boolean success = Math.random() > 0.05;
       
       if (success) {
           System.out.println("✅ CPU启动成功:" + model + " @ " + frequency + "GHz");
           isRunning = true;
           return true;
       } else {
           System.out.println("❌ CPU启动失败:温度异常");
           return false;
       }
      

      } catch (InterruptedException e) {
      System.out.println("❌ CPU启动过程被中断");
      return false;
      }
      }

    /**

    • 停止CPU运行
      */
      public boolean stop() {
      if (isRunning) {
      System.out.println("🛑 停止CPU运行");
      isRunning = false;
      return true;
      }
      return true;
      }

    /**

    • 获取CPU频率
      */
      public double getFrequency() {
      return frequency;
      }

    /**

    • 获取CPU状态
      */
      public String getStatus() {
      if (!isRunning) {
      return "未运行";
      }
      return "运行中 - " + model + " @ " + frequency + "GHz";
      }

    /**

    • 获取CPU型号
      */
      public String getModel() {
      return model;
      }
      }
  3. 子系统类 - 硬盘
    java
    // HardDisk.java - 硬盘子系统
    public class HardDisk {
    private long capacity; // GB
    private String type;
    private boolean isReady;

    public HardDisk(long capacity, String type) {
    this.capacity = capacity;
    this.type = type;
    this.isReady = false;
    }

    /**

    • 硬盘读取
      */
      public boolean read() {
      System.out.println("📖 硬盘读取中...");
      try {
      // 模拟读取过程
      Thread.sleep(1200);

       // 模拟读取结果(92%概率成功)
       boolean success = Math.random() > 0.08;
       
       if (success) {
           System.out.println("✅ 硬盘读取成功:" + capacity + "GB " + type);
           isReady = true;
           return true;
       } else {
           System.out.println("❌ 硬盘读取失败:发现坏道");
           return false;
       }
      

      } catch (InterruptedException e) {
      System.out.println("❌ 硬盘读取过程被中断");
      return false;
      }
      }

    /**

    • 硬盘写入
      */
      public boolean write() {
      if (!isReady) {
      System.out.println("❌ 硬盘未就绪,无法写入");
      return false;
      }
      System.out.println("📝 硬盘写入中...");
      return true;
      }

    /**

    • 获取硬盘容量
      */
      public long getCapacity() {
      return capacity;
      }

    /**

    • 获取硬盘类型
      */
      public String getType() {
      return type;
      }

    /**

    • 获取硬盘状态
      */
      public String getStatus() {
      if (!isReady) {
      return "未就绪";
      }
      return "就绪 - " + capacity + "GB " + type;
      }

    /**

    • 重置硬盘状态
      */
      public void reset() {
      isReady = false;
      System.out.println("🧹 硬盘状态已重置");
      }
      }
  4. 子系统类 - 操作系统
    java
    // OS.java - 操作系统子系统
    public class OS {
    private String name;
    private String version;
    private boolean isLoaded;

    public OS(String name, String version) {
    this.name = name;
    this.version = version;
    this.isLoaded = false;
    }

    /**

    • 加载操作系统
      */
      public boolean load() {
      System.out.println("🖥️ 加载操作系统中...");
      try {
      // 模拟加载过程
      Thread.sleep(2000);

       // 模拟加载结果(85%概率成功)
       boolean success = Math.random() > 0.15;
       
       if (success) {
           System.out.println("✅ 操作系统加载成功:" + name + " " + version);
           isLoaded = true;
           return true;
       } else {
           System.out.println("❌ 操作系统加载失败:系统文件损坏");
           return false;
       }
      

      } catch (InterruptedException e) {
      System.out.println("❌ 操作系统加载过程被中断");
      return false;
      }
      }

    /**

    • 关闭操作系统
      */
      public boolean shutdown() {
      if (isLoaded) {
      System.out.println("🔒 关闭操作系统中...");
      try {
      Thread.sleep(1000);
      System.out.println("✅ 操作系统已安全关闭");
      isLoaded = false;
      return true;
      } catch (InterruptedException e) {
      System.out.println("❌ 操作系统关闭过程被中断");
      return false;
      }
      }
      return true;
      }

    /**

    • 获取系统版本
      */
      public String getVersion() {
      return version;
      }

    /**

    • 获取系统名称
      */
      public String getName() {
      return name;
      }

    /**

    • 获取系统状态
      */
      public String getStatus() {
      if (!isLoaded) {
      return "未加载";
      }
      return "运行中 - " + name + " " + version;
      }
      }
  5. 外观类 - 计算机
    java
    // Computer.java - 计算机外观类
    public class Computer {
    private Memory memory;
    private CPU cpu;
    private HardDisk hardDisk;
    private OS os;
    private boolean isPoweredOn;

    public Computer() {
    // 初始化硬件配置
    this.memory = new Memory(16384); // 16GB
    this.cpu = new CPU("Intel Core i7", 3.6);
    this.hardDisk = new HardDisk(1024, "SSD"); // 1TB SSD
    this.os = new OS("Windows", "11 Pro");
    this.isPoweredOn = false;
    }

    public Computer(Memory memory, CPU cpu, HardDisk hardDisk, OS os) {
    this.memory = memory;
    this.cpu = cpu;
    this.hardDisk = hardDisk;
    this.os = os;
    this.isPoweredOn = false;
    }

    /**

    • 开机 - 外观模式的核心方法
      */
      public boolean powerOn() {
      System.out.println("🔌 开始启动计算机...");
      System.out.println("=" .repeat(40));

      // 1. 内存自检
      if (!memory.check()) {
      System.out.println("❌ 计算机启动失败:内存自检未通过");
      return false;
      }

      // 2. 启动CPU
      if (!cpu.run()) {
      System.out.println("❌ 计算机启动失败:CPU启动失败");
      return false;
      }

      // 3. 硬盘读取
      if (!hardDisk.read()) {
      System.out.println("❌ 计算机启动失败:硬盘读取失败");
      // 停止已启动的组件
      cpu.stop();
      return false;
      }

      // 4. 加载操作系统
      if (!os.load()) {
      System.out.println("❌ 计算机启动失败:操作系统加载失败");
      // 停止已启动的组件
      cpu.stop();
      hardDisk.reset();
      return false;
      }

      System.out.println("=" .repeat(40));
      System.out.println("🎉 计算机启动成功!");
      isPoweredOn = true;
      return true;
      }

    /**

    • 关机
      */
      public boolean powerOff() {
      System.out.println("🔌 开始关闭计算机...");

      boolean success = true;

      // 按顺序关闭各个组件
      if (!os.shutdown()) {
      success = false;
      }

      if (!cpu.stop()) {
      success = false;
      }

      hardDisk.reset();
      memory.reset();

      if (success) {
      System.out.println("✅ 计算机已安全关闭");
      isPoweredOn = false;
      } else {
      System.out.println("⚠️ 计算机关闭过程中出现问题");
      }

      return success;
      }

    /**

    • 强制关机
      */
      public boolean forceShutdown() {
      System.out.println("🛑 强制关闭计算机...");
      isPoweredOn = false;
      memory.reset();
      System.out.println("✅ 计算机已强制关闭");
      return true;
      }

    /**

    • 获取计算机状态
      */
      public String getStatus() {
      if (!isPoweredOn) {
      return "关机状态";
      }

      StringBuilder status = new StringBuilder();
      status.append("运行状态\n");
      status.append("├─ 内存: ").append(memory.getStatus()).append("\n");
      status.append("├─ CPU: ").append(cpu.getStatus()).append("\n");
      status.append("├─ 硬盘: ").append(hardDisk.getStatus()).append("\n");
      status.append("└─ 系统: ").append(os.getStatus());

      return status.toString();
      }

    /**

    • 获取系统信息
      */
      public String getSystemInfo() {
      StringBuilder info = new StringBuilder();
      info.append("=== 计算机配置信息 =\n");
      info.append("内存: ").append(memory.getSize() / 1024).append(" GB\n");
      info.append("CPU: ").append(cpu.getModel()).append(" @ ").append(cpu.getFrequency()).append("GHz\n");
      info.append("硬盘: ").append(hardDisk.getCapacity()).append(" GB ").append(hardDisk.getType()).append("\n");
      info.append("系统: ").append(os.getName()).append(" ").append(os.getVersion()).append("\n");
      info.append("
      ==================");

      return info.toString();
      }

    /**

    • 检查计算机是否开机
      */
      public boolean isPoweredOn() {
      return isPoweredOn;
      }

    // Getter方法
    public Memory getMemory() {
    return memory;
    }

    public CPU getCpu() {
    return cpu;
    }

    public HardDisk getHardDisk() {
    return hardDisk;
    }

    public OS getOs() {
    return os;
    }
    }

  6. 客户端类 - 主机
    java
    // Mainframe.java - 主机(客户端)
    public class Mainframe {
    private Computer computer;

    public Mainframe() {
    this.computer = new Computer();
    }

    public Mainframe(Computer computer) {
    this.computer = computer;
    }

    /**

    • 开机按钮 - 客户端只需要调用这个简单的方法
      */
      public boolean on() {
      System.out.println("🖲️ 按下开机按钮...");
      return computer.powerOn();
      }

    /**

    • 关机按钮
      */
      public boolean off() {
      System.out.println("🖲️ 按下关机按钮...");
      return computer.powerOff();
      }

    /**

    • 强制关机按钮
      */
      public boolean forceOff() {
      System.out.println("🖲️ 长按电源按钮强制关机...");
      return computer.forceShutdown();
      }

    /**

    • 获取系统信息
      */
      public String getSystemInfo() {
      return computer.getSystemInfo();
      }

    /**

    • 显示计算机状态
      */
      public void displayStatus() {
      System.out.println("=== 计算机状态 =");
      System.out.println(computer.getStatus());
      System.out.println("
      ===============");
      }

    /**

    • 重启计算机
      */
      public boolean restart() {
      System.out.println("🔄 重启计算机...");

      if (computer.isPoweredOn()) {
      if (!computer.powerOff()) {
      System.out.println("⚠️ 关机失败,尝试强制重启");
      computer.forceShutdown();
      }
      }

      // 等待一段时间再开机
      try {
      Thread.sleep(2000);
      } catch (InterruptedException e) {
      System.out.println("重启过程被中断");
      }

      return computer.powerOn();
      }
      }

  7. 测试演示类
    java
    // FacadePatternDemo.java - 外观模式演示
    public class FacadePatternDemo {

    // 演示基本外观模式
    public static void demonstrateBasicFacade() {
    System.out.println("=== 基本外观模式演示 ===");

     Mainframe mainframe = new Mainframe();
     
     System.out.println("\n1. 显示系统信息:");
     System.out.println(mainframe.getSystemInfo());
     
     System.out.println("\n2. 开机过程:");
     boolean success = mainframe.on();
     
     if (success) {
         System.out.println("\n3. 开机后状态:");
         mainframe.displayStatus();
         
         System.out.println("\n4. 关机过程:");
         mainframe.off();
     }
    

    }

    // 演示外观模式的优势
    public static void demonstrateFacadeAdvantages() {
    System.out.println("\n\n=== 外观模式优势演示 ===");

     System.out.println("没有外观模式的情况:");
     System.out.println("客户端需要了解所有子系统的细节:");
     
     // 模拟没有外观模式的复杂调用
     Memory memory = new Memory(8192);
     CPU cpu = new CPU("AMD Ryzen 5", 3.4);
     HardDisk hardDisk = new HardDisk(512, "HDD");
     OS os = new OS("Linux", "Ubuntu 22.04");
     
     System.out.println("\n手动启动计算机:");
     if (!memory.check()) {
         System.out.println("启动失败");
         return;
     }
     if (!cpu.run()) {
         System.out.println("启动失败");
         return;
     }
     if (!hardDisk.read()) {
         System.out.println("启动失败");
         cpu.stop();
         return;
     }
     if (!os.load()) {
         System.out.println("启动失败");
         cpu.stop();
         hardDisk.reset();
         return;
     }
     System.out.println("手动启动成功!");
     
     System.out.println("\n使用外观模式的情况:");
     Computer computer = new Computer(memory, cpu, hardDisk, os);
     Mainframe mainframe = new Mainframe(computer);
     System.out.println("只需要调用一个方法:");
     mainframe.on();
    

    }

    // 演示错误处理
    public static void demonstrateErrorHandling() {
    System.out.println("\n\n=== 错误处理演示 ===");

     System.out.println("模拟多次启动,展示可能的错误情况:");
     
     for (int i = 1; i <= 5; i++) {
         System.out.println("\n--- 第 " + i + " 次启动尝试 ---");
         Mainframe mainframe = new Mainframe();
         boolean success = mainframe.on();
         
         if (success) {
             System.out.println("🎉 启动成功!");
             mainframe.displayStatus();
             
             // 正常关机
             mainframe.off();
         } else {
             System.out.println("💥 启动失败!");
         }
     }
    

    }

    // 演示实际应用场景
    public static void demonstrateRealWorldScenario() {
    System.out.println("\n\n=== 实际应用场景演示 ===");

     System.out.println("场景:用户使用计算机");
     
     Mainframe myComputer = new Mainframe();
     
     System.out.println("\n1. 用户按下开机按钮:");
     if (myComputer.on()) {
         System.out.println("\n2. 用户查看系统状态:");
         myComputer.displayStatus();
         
         System.out.println("\n3. 用户使用计算机一段时间后...");
         try {
             Thread.sleep(1000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         
         System.out.println("\n4. 用户按下关机按钮:");
         myComputer.off();
     } else {
         System.out.println("计算机启动失败,请联系技术支持");
     }
    

    }

    // 演示重启功能
    public static void demonstrateRestart() {
    System.out.println("\n\n=== 重启功能演示 ===");

     Mainframe mainframe = new Mainframe();
     
     System.out.println("1. 首次启动:");
     if (mainframe.on()) {
         System.out.println("\n2. 执行重启:");
         if (mainframe.restart()) {
             System.out.println("\n3. 重启后状态:");
             mainframe.displayStatus();
             
             System.out.println("\n4. 最终关机:");
             mainframe.off();
         }
     }
    

    }

    // 比较外观模式与其他模式
    public static void compareWithOtherPatterns() {
    System.out.println("\n\n=== 外观模式与其他模式比较 ===");

     System.out.println("外观模式 vs 其他结构型模式:");
     System.out.println("┌─────────────────┬───────────────────┬──────────────────┬──────────────────┐");
     System.out.println("│     模式        │     主要目的      │    适用场景      │    特点          │");
     System.out.println("├─────────────────┼───────────────────┼──────────────────┼──────────────────┤");
     System.out.println("│   外观模式      │ 简化复杂系统接口  │ 复杂子系统调用    │ 提供统一接口     │");
     System.out.println("│   适配器模式    │ 接口转换          │ 接口不兼容        │ 转换接口格式     │");
     System.out.println("│   装饰器模式    │ 动态添加功能      │ 需要扩展功能      │ 透明包装对象     │");
     System.out.println("│   组合模式      │ 处理树形结构      │ 部分-整体结构     │ 统一处理叶子容器 │");
     System.out.println("└─────────────────┴───────────────────┴──────────────────┴──────────────────┘");
     
     System.out.println("\n外观模式的优势:");
     System.out.println("1. 简化客户端:客户端不需要了解子系统的复杂细节");
     System.out.println("2. 解耦合:将客户端与子系统解耦,提高子系统的独立性");
     System.out.println("3. 易于使用:提供简单一致的接口");
     System.out.println("4. 层次化结构:可以定义多个外观类,为不同层次的客户端服务");
    

    }

    public static void main(String[] args) {
    System.out.println("实验12:外观模式 - 计算机开启");
    System.out.println("=========================================");

     demonstrateBasicFacade();
     demonstrateFacadeAdvantages();
     demonstrateErrorHandling();
     demonstrateRealWorldScenario();
     demonstrateRestart();
     compareWithOtherPatterns();
     
     System.out.println("\n=== 实验总结 ===");
     System.out.println("1. 外观模式为复杂的子系统提供一个统一的简单接口");
     System.out.println("2. 客户端只需要与外观类交互,不需要了解子系统的细节");
     System.out.println("3. 降低了客户端与子系统的耦合度");
     System.out.println("4. 符合迪米特法则(最少知识原则)");
     System.out.println("5. 在实际应用中,外观模式常用于框架设计、API封装等场景");
    

    }
    }

posted @ 2025-11-14 22:21  头发少的文不识  阅读(7)  评论(0)    收藏  举报