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 小时前
深入浅出传输层:UDP 与 TCP 协议全景指南
linux·服务器·网络·c++·笔记·tcp/ip·udp
Chester_19997 小时前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
会周易的程序员8 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
小灰灰搞电子9 小时前
完全驾驭 Qt 与数据库:C++ ORM 框架 QxOrm 原理与实践指南
数据库·c++·qt
QT界面美化性能优化9 小时前
QT+AI:使用AI技术为QT应用程序赋能
c++·人工智能·qt·opencv·qt教程·qt6.3
学习星球11 小时前
单调栈——从“找下一个更大的“到柱状图中的最大矩形
数据库·c++·算法·leetcode·xcode
小灰灰搞电子12 小时前
C++ 引用折叠详解
c++
workflower12 小时前
人形机器人灵巧手产业链
人工智能·设计模式·机器人·云计算·无人机
布莱克60512 小时前
数组详解:定义、作用、应用场景及与链表的区别(C/C++ 代码讲解)
c语言·开发语言·c++·数组
牛油果子哥q13 小时前
C++内存池与对象池精讲:内存碎片、自定义分配器、对象池实现、STL allocator原理、工程落地与性能对比
java·开发语言·c++