C++ 外观模式详解

发布于:2025-05-19 ⋅ 阅读:(15) ⋅ 点赞:(0)

外观模式(Facade Pattern)是一种结构型设计模式,它为复杂的子系统提供一个简化的接口。

概念解析

外观模式的核心思想是:

  1. 简化接口:为复杂的子系统提供一个更简单、更统一的接口

  2. 降低耦合:减少客户端与子系统之间的直接依赖

  3. 封装复杂性:隐藏子系统的内部复杂性

主要组成部分

  1. 外观(Facade):提供简化的接口,将客户端的请求委派给适当的子系统对象

  2. 子系统类(Subsystem Classes):实现子系统的功能,处理外观对象指派的工作

  3. 客户端(Client):通过外观接口与子系统交互

代码示例

下面是一个完整的外观模式示例,包含详细注释:

#include <iostream>
#include <string>
#include <memory>

// ==================== 子系统类 ====================

// 库存子系统
class Inventory {
public:
    bool checkStock(const std::string& item, int quantity) {
        std::cout << "检查库存: " << item << " 数量 " << quantity << std::endl;
        // 模拟库存检查
        return true; // 假设总是有库存
    }
};

// 支付子系统
class Payment {
public:
    bool processPayment(double amount, const std::string& paymentMethod) {
        std::cout << "处理支付: " << amount << " 通过 " << paymentMethod << std::endl;
        // 模拟支付处理
        return true; // 假设支付总是成功
    }
};

// 物流子系统
class Shipping {
public:
    std::string shipOrder(const std::string& item, const std::string& address) {
        std::cout << "发货: " << item << " 到 " << address << std::endl;
        // 模拟物流处理
        return "ORD123456"; // 返回订单号
    }
};

// 通知子系统
class Notification {
public:
    void sendConfirmation(const std::string& orderId, const std::string& email) {
        std::cout << "发送确认邮件到 " << email 
                  << ", 订单号: " << orderId << std::endl;
    }
};

// ==================== 外观类 ====================
class OrderFacade {
private:
    std::unique_ptr<Inventory> inventory;
    std::unique_ptr<Payment> payment;
    std::unique_ptr<Shipping> shipping;
    std::unique_ptr<Notification> notification;

public:
    OrderFacade() 
        : inventory(std::make_unique<Inventory>()),
          payment(std::make_unique<Payment>()),
          shipping(std::make_unique<Shipping>()),
          notification(std::make_unique<Notification>()) {}

    // 简化的一站式下单接口
    std::string placeOrder(
        const std::string& item,
        int quantity,
        double amount,
        const std::string& paymentMethod,
        const std::string& address,
        const std::string& email) {
        
        std::cout << "\n开始处理订单..." << std::endl;

        // 1. 检查库存
        if (!inventory->checkStock(item, quantity)) {
            throw std::runtime_error(item + " 库存不足");
        }

        // 2. 处理支付
        if (!payment->processPayment(amount, paymentMethod)) {
            throw std::runtime_error("支付处理失败");
        }

        // 3. 发货
        std::string orderId = shipping->shipOrder(item, address);

        // 4. 发送确认通知
        notification->sendConfirmation(orderId, email);

        std::cout << "订单处理完成!" << std::endl;
        return orderId;
    }

    // 也可以提供子系统功能的单独访问方法
    bool checkInventory(const std::string& item, int quantity) {
        return inventory->checkStock(item, quantity);
    }
};

// ==================== 客户端代码 ====================
int main() {
    std::cout << "=== 外观模式演示 ===" << std::endl;

    // 创建外观对象
    OrderFacade orderFacade;

    // 使用简化接口下单
    try {
        std::string orderId = orderFacade.placeOrder(
            "笔记本电脑", 
            1, 
            999.99, 
            "信用卡", 
            "北京市海淀区", 
            "customer@example.com");
        
        std::cout << "\n订单创建成功! 订单号: " << orderId << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "订单失败: " << e.what() << std::endl;
    }

    // 也可以直接访问子系统的部分功能
    std::cout << "\n直接检查库存:" << std::endl;
    bool inStock = orderFacade.checkInventory("鼠标", 5);
    std::cout << "库存检查结果: " << (inStock ? "有库存" : "缺货") << std::endl;

    return 0;
}

模式优势

  1. 简化接口:为复杂子系统提供简单易懂的接口

  2. 解耦:减少客户端与子系统的直接依赖

  3. 易于使用:客户端不需要了解子系统内部细节

  4. 灵活性:可以随时修改子系统而不影响客户端

  5. 层次化:有助于实现系统的层次结构

适用场景

  1. 当需要为复杂的子系统提供一个简单接口时

  2. 当客户端与子系统之间存在大量依赖关系时

  3. 当需要将子系统分层时,可以使用外观模式定义每层的入口点

  4. 当需要封装遗留系统或第三方复杂库时

  5. 当需要简化测试复杂子系统时


网站公告

今日签到

点亮在社区的每一天
去签到