Java学设计模式之外观模式

一、外观模式概念

1.1 什么是外观模式

外观模式是一种结构型设计模式,它提供了一个统一的接口,用于访问子系统中的一组接口。外观模式定义了一个高级接口,这个接口使得子系统更容易使用,同时隐藏了子系统的复杂性。

结构

外观模式通常由以下几个部分组成:

  1. Facade(外观): 提供了一个高级接口,用于访问子系统的功能。外观模式的客户端只与外观对象交互,而不直接与子系统中的对象交互。
  2. Subsystem(子系统): 实现了系统的功能。外观模式通过将客户端请求委派给子系统中的对象来完成操作。

二、外观模式代码

2.1 子系统

public class CPU {
public void start() {
System.out.println("CPU is starting...");
}
public void shutdown() {
System.out.println("CPU is shutting down...");
}
}
public class Memory {
public void load() {
System.out.println("Memory is loading data...");
}
public void free() {
System.out.println("Memory is freeing data...");
}
}
public class HardDrive {
public void read() {
System.out.println("Hard Drive is reading data...");
}
public void write() {
System.out.println("Hard Drive is writing data...");
}
}

2.2 外观

class ComputerFacade {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public ComputerFacade() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}
public void start() {
cpu.start();
memory.load();
hardDrive.read();
System.out.println("Computer is starting...");
}
public void shutdown() {
cpu.shutdown();
memory.free();
hardDrive.write();
System.out.println("Computer is shutting down...");
}
}

2.3 测试类

public class FacadePatternTest {
public static void main(String[] args) {
ComputerFacade computer = new ComputerFacade();
computer.start();
System.out.println("--------------");
computer.shutdown();
// 输出:
// CPU is starting...
// Memory is loading data...
// Hard Drive is reading data...
// Computer is starting...
// --------------
// CPU is shutting down...
// Memory is freeing data...
// Hard Drive is writing data...
// Computer is shutting down...
}
}

三、总结

外观模式的优点包括:

  • 简化了客户端与子系统之间的交互,客户端只需要与外观对象交互,而不需要了解子系统的复杂性。
  • 降低了子系统与客户端之间的耦合度,子系统的变化不会影响到客户端。

缺点包括:

  • 如果系统变得过于复杂,外观对象本身可能会变得庞大,难以维护。
  • 外观模式隐藏了系统的复杂性,可能会导致客户端对系统的实际情况缺乏了解。

本文作者:启航黑珍珠号

本文链接:https://www.cnblogs.com/Linzj5950/p/18182498

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   启航黑珍珠号  阅读(34)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起