设备间有多种通讯方式,但是接口基本类似,应该采用什么样的设计模式呢?

在C++中,针对需要对接不同通信方式(如TCP、串口)但功能接口类似(如开始、停止)的场景,推荐采用策略模式(Strategy Pattern) 结合 **工厂模式(Factory Pattern)**来实现。以下是具体分析和实现步骤:


1. 策略模式(Strategy Pattern)

核心思想:将每种通信方式封装为独立的策略类,实现统一的接口,使得客户端可以动态切换具体实现,而无需修改调用逻辑。

步骤实现
  1. 定义抽象接口 :声明所有通信方式共有的方法(如start()stop())。
  2. 实现具体策略:为TCP、串口等通信方式创建具体类,继承并实现接口。
  3. 客户端通过接口调用:客户端代码依赖抽象接口,而非具体实现,实现解耦。
cpp 复制代码
// 抽象接口
class CommunicationInterface {
public:
    virtual ~CommunicationInterface() = default;
    virtual void start() = 0;
    virtual void stop() = 0;
    virtual void send(const std::string& data) = 0;
    virtual std::string receive() = 0;
};

// TCP通信策略
class TcpCommunication : public CommunicationInterface {
public:
    void start() override { /* TCP启动逻辑 */ }
    void stop() override { /* TCP停止逻辑 */ }
    void send(const std::string& data) override { /* TCP发送数据 */ }
    std::string receive() override { /* TCP接收数据 */ return ""; }
};

// 串口通信策略
class SerialCommunication : public CommunicationInterface {
public:
    void start() override { /* 串口启动逻辑 */ }
    void stop() override { /* 串口停止逻辑 */ }
    void send(const std::string& data) override { /* 串口发送数据 */ }
    std::string receive() override { /* 串口接收数据 */ return ""; }
};

2. 工厂模式(Factory Pattern)

核心思想:通过工厂类封装对象的创建逻辑,客户端无需关心具体类的实例化过程。

步骤实现
  1. 定义通信类型枚举:标识支持的通信方式。
  2. 实现工厂类:根据类型参数返回对应的策略对象。
cpp 复制代码
enum class CommunicationType { TCP, SERIAL };

class CommunicationFactory {
public:
    static std::unique_ptr<CommunicationInterface> create(CommunicationType type) {
        switch (type) {
            case CommunicationType::TCP:
                return std::make_unique<TcpCommunication>();
            case CommunicationType::SERIAL:
                return std::make_unique<SerialCommunication>();
            default:
                throw std::invalid_argument("Unsupported communication type");
        }
    }
};

3. 客户端代码

客户端通过工厂获取具体策略对象,并通过抽象接口操作通信逻辑。

cpp 复制代码
int main() {
    // 根据配置或用户输入选择通信方式
    auto comm = CommunicationFactory::create(CommunicationType::TCP);

    // 统一接口调用
    comm->start();
    comm->send("Hello, World!");
    auto response = comm->receive();
    comm->stop();

    return 0;
}

优势

  1. 开闭原则:新增通信方式时,只需添加新的策略类和更新工厂,无需修改现有代码。
  2. 解耦:客户端代码与具体通信实现解耦,依赖抽象接口。
  3. 可维护性:不同通信方式的逻辑隔离,易于单独测试和维护。

扩展性优化

  • 注册式工厂:通过动态注册策略类的方式,避免工厂类硬编码具体类型,进一步提升扩展性。
  • 依赖注入:结合依赖注入框架,动态注入具体策略对象。

最终方案策略模式 + 工厂模式,既实现了不同通信方式的无缝切换,又保证了代码的简洁性和可扩展性。

相关推荐
静水流深_沧海一粟9 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder9 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室16 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦1 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20105 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈5 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||5 天前
安装依赖三方exe/msi的软件设计模式
设计模式