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 小时前
【数据结构】二叉树-堆(树的概念、二叉树的概念、顺序结构的结构及实现、堆的实现、堆排序、TopK问题)
c语言·数据结构·c++·经验分享·算法·青少年编程
ximu_polaris2 小时前
设计模式(C++)-结构型模式-桥接模式
c++·设计模式·桥接模式
楼田莉子2 小时前
仿muduo库的高并发服务器——正则表达式与any类介绍及其简单模拟实现
linux·服务器·c++·学习·设计模式
workflower2 小时前
机器人应用-室外区域巡逻
人工智能·设计模式·机器人·软件工程·软件构建
wengqidaifeng3 小时前
C++从菜鸟到强手:1.基础入门
开发语言·c++
geovindu4 小时前
go: Flyweight Pattern
开发语言·设计模式·golang·享元模式
handler0111 小时前
从源码到二进制:深度拆解 Linux 下 C 程序的编译与链接全流程
linux·c语言·开发语言·c++·笔记·学习
t***54412 小时前
如何在Dev-C++中使用Clang编译器
开发语言·c++
Qbw200412 小时前
【Linux】进程地址空间
linux·c++