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
    • 各模块独立,易于测试、扩展和维护。
相关推荐
咖啡八杯2 小时前
GoF设计模式——解释器模式
java·后端·spring·设计模式
同勉共进3 小时前
记一例 vibe coding + gcc bug 导致的线程池死锁问题
c++·线程池·gcc·死锁·vibe coding
我叫洋洋3 小时前
C ++ [ hello world ]
c语言·c++·算法
大数据新鸟4 小时前
设计模式四大基本原则
设计模式
王维同学7 小时前
[自学][Windows C++]RunOnceEx 注册表分组键的安全遍历
c++·windows·安全·开源
Scott9999HH8 小时前
告别流量波动玄学!从法拉第电磁定律到底层 C/C++ 流量累积算法,深度解密工业级电磁流量计选型与开发
c语言·c++·算法
脱胎换骨-军哥8 小时前
C++/Rust无缝互操作:混合系统新常态
开发语言·c++·rust
旖-旎10 小时前
LeetCode 279:完全平方数(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
南一Nanyi10 小时前
依赖注入和控制反转
前端·设计模式·nestjs
胖大和尚11 小时前
C++ 多线程编程的实现方式
c++·thread