C++设计模式(高内聚,低耦合)

1.高内聚,低耦合

High Cohesion:

一个模块/类内部的功能紧密相关,只负责一件事(单一职责)

Low Coupling

模块之间依赖关系尽量少,一个模块的变化不影响其他模块。

cpp 复制代码
#include <iostream>
#include <string>

// 🔹 负责银行转账逻辑(高内聚:只管钱的事)
class BankAccount {
public:
    void transfer(double amount, const std::string& from, const std::string& to) {
        std::cout << "Processing transfer: " << amount << " from " << from << " to " << to << std::endl;
    }
};

// 🔹 负责发送通知(高内聚:只管通知的事)
class NotificationService {
public:
    virtual void sendNotification(const std::string& message) = 0;  // 抽象接口
};

class EmailService : public NotificationService {
public:
    void sendNotification(const std::string& message) override {
        std::cout << "[EMAIL] " << message << std::endl;
    }
};

// 🔹 负责记录日志(高内聚:只管日志的事)
class Logger {
public:
    void log(const std::string& event) {
        std::cout << "[LOG] " << event << std::endl;
    }
};

// 🔹 转账服务(协调其他组件,但依赖抽象接口,低耦合)
class TransferService {
private:
    BankAccount account;
    NotificationService* notifier;  // 依赖抽象,而不是具体实现
    Logger logger;

public:
    TransferService(NotificationService* n) : notifier(n) {}

    void executeTransfer(double amount, const std::string& from, const std::string& to) {
        account.transfer(amount, from, to);
        logger.log("Transfer completed: " + std::to_string(amount));
        notifier->sendNotification("Transfer successful!");
    }
};

int main() {
    EmailService emailNotifier;  // 具体实现
    TransferService service(&emailNotifier);

    service.executeTransfer(1000.0, "Alice", "Bob");

    return 0;
}
  • 高内聚
    • BankAccount 只管转账;
    • EmailService 只管发邮件;
    • Logger 只管记录日志;
  • 低耦合
    • TransferService 依赖 NotificationService 接口,不关心具体是邮件还是短信;
    • 如果要换短信服务,只需实现 NotificationService 接口,无需修改 TransferService
    • 各模块独立,易于测试、扩展和维护。
相关推荐
咖啡八杯1 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
玖玥拾2 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you3 小时前
constexpr函数
c++
凡人叶枫3 小时前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫3 小时前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss4 小时前
BRpc使用
c++·rpc
-森屿安年-4 小时前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream4 小时前
Cartographer详细讲解
c++·人工智能·自动驾驶
森G4 小时前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
碧海蓝天20224 小时前
C++法则24:在标准 C++ 中,没有任何可移植的方式判断指针 T* pt 指向的内存位置是否已经 构造了对象,程序员必须手动跟踪哪些元素已构造。
java·开发语言·c++