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
相关推荐
灯澜忆梦1 小时前
GO_面向对象_方法
开发语言·golang
布朗克1681 小时前
Go 入门到精通-16-字符串深入
开发语言·后端·golang·字符串
北冥you鱼2 小时前
Go flag 包详解:从命令行解析到实战应用
开发语言·后端·golang
炸膛坦客2 小时前
单片机/C/C++八股:(二十四)编译文件( .bin 和 .hex ,包括 .elf 和 .axf )
c语言·c++·单片机
web守墓人2 小时前
【python】uv解决依赖安装缓慢的问题
开发语言·python·uv
cpp_25013 小时前
P10098 [ROIR 2023] 地铁建设 (Day 2)
数据结构·c++·算法·贪心·二分答案·洛谷题解
geovindu4 小时前
CSharp: Bridge Pattern
开发语言·后端·桥接模式·结构型模式
hehelm4 小时前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++
এ慕ོ冬℘゜4 小时前
深入 JavaScript BOM:掌握 window 对象的窗口控制魔法
开发语言·javascript·ecmascript