My App

外观模式

Facade — 为复杂子系统提供一个统一的简单入口

一句话理解

把一堆复杂的子系统藏在一个简单接口后面,调用方只需要和这个"前台"打交道。

解决什么问题

  • 子系统内部有很多类,互相依赖,外部调用者不应该直接面对这些复杂性
  • 想给外部提供一个简化的、统一的入口

怎么写

// 复杂的子系统
class CPU {
    void start() { System.out.println("CPU 启动"); }
    void shutdown() { System.out.println("CPU 关闭"); }
}

class Memory {
    void load() { System.out.println("内存加载"); }
    void clear() { System.out.println("内存清理"); }
}

class Disk {
    void read() { System.out.println("磁盘读取"); }
    void stop() { System.out.println("磁盘停止"); }
}

// 外观类:把复杂操作封装成简单方法
public class Computer {
    private final CPU cpu = new CPU();
    private final Memory memory = new Memory();
    private final Disk disk = new Disk();

    public void start() {
        cpu.start();
        memory.load();
        disk.read();
        System.out.println("电脑启动完成!");
    }

    public void shutdown() {
        disk.stop();
        memory.clear();
        cpu.shutdown();
        System.out.println("电脑已关机");
    }
}
// 使用:一行搞定,不需要知道内部细节
Computer computer = new Computer();
computer.start();     // 自动按顺序启动所有子系统
computer.shutdown();  // 自动按顺序关闭

前端中的外观

// 封装复杂的浏览器 API 为简单接口
const storage = {
  get(key: string) {
    const item = localStorage.getItem(key)
    return item ? JSON.parse(item) : null
  },
  set(key: string, value: any) {
    localStorage.setItem(key, JSON.stringify(value))
  },
  remove(key: string) {
    localStorage.removeItem(key)
  },
}

// 使用:不用每次手动 JSON.parse / JSON.stringify
storage.set('user', { name: '张三' })
storage.get('user')  // { name: '张三' }

使用场景

  • SLF4J —— 日志门面,背后可以是 Logback、Log4j 等
  • Spring 的 JdbcTemplate —— 把 JDBC 的繁琐操作封装成简单方法
  • 各种 SDK —— 把复杂 API 封装成几个简单方法
  • 前端的 axios 封装层 —— 统一处理 baseURL、拦截器、错误处理

On this page