C++设计策略模式

继承同一接口,各自实现不同算法

override:明确在重写基类虚函数

go(from, to):所有出行方式都必须实现的接口

virtual void go(const std::string& from, const std::string& to)= 0:纯虚函数 → 这是抽象类,不能直接 TravelStrategy x;

两个关键点:

1)持有策略,不写死类型

std::unique_ptr<TravelStrategy> strategy_;

类型是基类指针/智能指针 → 可以指向 CarStrategy 或 WalkStrategy。

2)travel 只调接口,不写 if

strategy_->go(from, to);

Navigator 不知道现在是开车还是走路;只知道让当前策略 go。

std::make_unique<CarStrategy>() ------>相当于

// 示意

CarStrategy* raw = new CarStrategy(); // 1. 堆上 new 对象

std::unique_ptr<TravelStrategy> temp(raw); // 2. 用 unique_ptr 管住它

// (基类指针可指向派生类)

return temp; // 3. 返回这个 unique_ptr指针管理对象

  1. 造出临时 unique_ptr(叫 temp)

  2. 初始化参数 s 时:

移动构造

s.p = temp.p; // s 拿到地址

temp.p = nullptr; // temp 变空

复制代码
#include <memory>
#include <cstdio>
#include <string>

// 抽象策略:怎么出行
struct TravelStrategy {
    virtual ~TravelStrategy() = default;
    virtual void go(const std::string& from, const std::string& to) = 0;
};

struct CarStrategy : TravelStrategy {
    void go(const std::string& from, const std::string& to) override {
        std::printf("drive %s -> %s\n", from.c_str(), to.c_str());
    }
};

struct WalkStrategy : TravelStrategy {
    void go(const std::string& from, const std::string& to) override {
        std::printf("walk %s -> %s\n", from.c_str(), to.c_str());
    }
};

// Context:导航
class Navigator {
    std::unique_ptr<TravelStrategy> strategy_;
public:
    void setStrategy(std::unique_ptr<TravelStrategy> s) {
        strategy_ = std::move(s);
    }
    void travel(const std::string& from, const std::string& to) {
        strategy_->go(from, to);  // 不关心是开车还是走路
    }
};

int main() {
    Navigator nav;
    nav.setStrategy(std::make_unique<CarStrategy>());
    nav.travel("home", "office");   // drive ...

    nav.setStrategy(std::make_unique<WalkStrategy>());
    nav.travel("home", "office");   // walk ...
}

执行调用顺序:

复制代码
1. 创建 Navigator(此时还没有策略,实际用前要先 set)

2. setStrategy(CarStrategy)
      Navigator.strategy_ ──► [CarStrategy 对象]

3. travel("home","office")
      Navigator ──调用──► CarStrategy::go
      屏幕:drive home -> office

4. setStrategy(WalkStrategy)
      旧 CarStrategy 销毁
      Navigator.strategy_ ──► [WalkStrategy 对象]

5. travel("home","office")
      Navigator ──调用──► WalkStrategy::go
      屏幕:walk home -> office
相关推荐
码匠许师傅13 分钟前
【C++三方组件】Qt 概览:桌面 C++ 的事实标准与许可证三轨
开发语言·c++·qt
码匠许师傅1 小时前
【C++三方组件】POCO:跨平台系统编程全家桶
开发语言·c++
bkspiderx2 小时前
基于Socket的广播通信及C语言实现详解
c语言·开发语言·socket·广播·socket的广播通信
小王C语言2 小时前
Qt常用控件:输入类控件,单行/多行输入框、下拉框、(日期)微调框、旋钮、滑动条
开发语言·qt
ESDWAN2 小时前
SD-WAN 主备切换为什么仍然会断网?从检测机制到会话恢复分析
开发语言·php
1001101_QIA2 小时前
.exe does not seem to be a Qt executable.
开发语言·qt
echome8882 小时前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
云和数据.ChenGuang2 小时前
Python 单继承与多继承深度剖析:从 MRO 到实战取舍
开发语言·人工智能·python·langchain
小咕聊编程3 小时前
基于Python的豆瓣电影数据可视化系统构建分析
开发语言·python·信息可视化
WBluuue4 小时前
数据结构与算法:分块(一):块状数组、块状链表
数据结构·c++·算法·链表