c++设计模式之策略模式

  1. 策略模式(Strategy Pattern)
    定义
    策略模式定义了一系列算法(或操作),并将每个算法封装在一个类中,使它们可以互换。策略模式的核心思想是将选择算法的责任从使用算法的类中分离出来,从而使得算法可以独立变化。

应用场景

当系统需要根据不同的条件选择不同的算法或行为时,策略模式是一个理想的解决方案。

例如,监控软件在与不同型号的交换机交互时,可能需要根据交换机的配置策略、管理需求等选择不同的操作策略。

结构

Context(上下文):使用策略的对象,持有一个对策略的引用,并委托任务给具体的策略对象。

Strategy(策略接口):定义一个接口,所有的具体策略类都实现该接口。

ConcreteStrategy(具体策略类):实现具体的算法或操作。

代码示例

假设我们需要根据不同的网络环境选择不同的连接策略(例如,基于串口、SSH或Telnet连接设备)。

2.1 定义策略接口

cpp 复制代码
cpp
// ConnectionStrategy.h
#ifndef CONNECTION_STRATEGY_H
#define CONNECTION_STRATEGY_H

class ConnectionStrategy {
public:
    virtual void connect() = 0;
    virtual ~ConnectionStrategy() {}
};

#endif // CONNECTION_STRATEGY_H


2.2 定义具体策略类
cpp
// SerialConnection.h
#ifndef SERIAL_CONNECTION_H
#define SERIAL_CONNECTION_H

#include "ConnectionStrategy.h"
#include <iostream>

class SerialConnection : public ConnectionStrategy {
public:
    void connect() override {
        std::cout << "Connecting via Serial Port..." << std::endl;
    }
};

#endif // SERIAL_CONNECTION_H
cpp
// SSHConnection.h
#ifndef SSH_CONNECTION_H
#define SSH_CONNECTION_H

#include "ConnectionStrategy.h"
#include <iostream>

class SSHConnection : public ConnectionStrategy {
public:
    void connect() override {
        std::cout << "Connecting via SSH..." << std::endl;
    }
};

#endif // SSH_CONNECTION_H
2.3 定义上下文类
cpp
// NetworkManager.h
#ifndef NETWORK_MANAGER_H
#define NETWORK_MANAGER_H

#include "ConnectionStrategy.h"

class NetworkManager {
private:
    ConnectionStrategy* connectionStrategy;

public:
    NetworkManager(ConnectionStrategy* strategy) : connectionStrategy(strategy) {}

    void setConnectionStrategy(ConnectionStrategy* strategy) {
        connectionStrategy = strategy;
    }

    void connect() {
        connectionStrategy->connect();
    }
};

#endif // NETWORK_MANAGER_H
2.4 使用策略
cpp
// Main.cpp
#include "NetworkManager.h"
#include "SerialConnection.h"
#include "SSHConnection.h"

int main() {
    ConnectionStrategy* serial = new SerialConnection();
    ConnectionStrategy* ssh = new SSHConnection();

    NetworkManager manager(serial);
    manager.connect();  // Output: Connecting via Serial Port...

    manager.setConnectionStrategy(ssh);
    manager.connect();  // Output: Connecting via SSH...

    delete serial;
    delete ssh;

    return 0;
}

解释

ConnectionStrategy 定义了连接的接口。

相关推荐
2401_892070981 天前
【Linux C++ 日志系统实战】LogFile 日志文件管理核心:滚动策略、线程安全与方法全解析
linux·c++·日志系统·日志滚动
yuzhuanhei1 天前
Visual Studio 配置C++opencv
c++·学习·visual studio
不爱吃炸鸡柳1 天前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发1 天前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射
Momentary_SixthSense1 天前
设计模式之工厂模式
java·开发语言·设计模式
Java码农也是农1 天前
Multi-Agent 系统设计模式
设计模式·agent·multi-agent
sg_knight1 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
‎ദ്ദിᵔ.˛.ᵔ₎1 天前
STL 栈 队列
开发语言·c++
2401_892070981 天前
【Linux C++ 日志系统实战】高性能文件写入 AppendFile 核心方法解析
linux·c++·日志系统·文件写对象
郭涤生1 天前
STL vector 扩容机制与自定义内存分配器设计分析
c++·算法