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
    • 各模块独立,易于测试、扩展和维护。
相关推荐
此生决int14 小时前
深入理解C++系列(10)——lsit
开发语言·c++
NoteStream14 小时前
【C语言基础】分支和循环(上)
c语言·开发语言·c++·经验分享·笔记·算法·c#
2401_8274999914 小时前
C++(黑马)05-提高编程
java·开发语言·c++
hold?fish:palm15 小时前
链表的基本原理和实现(C++版本)
数据结构·c++·链表
jufeng130715 小时前
【系列:MiniKV 原理剖析 · 第 5 篇】
linux·网络·c++·软件工程
今天的砖头有点烫手啊16 小时前
AI Agent 开发实战(十):Agent 设计模式(ReAct / Plan-Execute / Reflection)
人工智能·react.js·设计模式
豆沙沙包?16 小时前
C++-程序的内存模型(P84-P88)
java·jvm·c++
董员外16 小时前
RAG 系统进化论(十):可运营 RAG,从原型到长期运行的知识系统
人工智能·后端·设计模式
jufeng130716 小时前
【系列:MiniKV 原理剖析 · 第 8 篇(完结篇)】
linux·c++·log4j·软件工程·makefile
VL——MOESR16 小时前
【LuoguP1967】货车运输【生成树】【倍增】
c++·算法·题解·倍增·生成树