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
相关推荐
名字还没想好☜31 分钟前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
酷在前行2 小时前
【R生态】PERMANOVA 进阶实战:距离选择、PERMDISP、两两比较与受限置换(保姆级教程)
开发语言·r语言
cxr8283 小时前
Graphify vs GitNexus vs CodeGraph — 三工具架构深度对比
开发语言·架构·知识图谱
清水迎朝阳3 小时前
客户端软件 — 用户统计方案
服务器·c++·客户端·用户统计
废弃的小码农4 小时前
功能测试--Day07--Python编程基础
开发语言·python
再卷也是菜4 小时前
C++17(下)
c++
fengci.4 小时前
Microweber CMS 未授权路径穿越漏洞(CVE-2026-65694)
android·开发语言·前端·学习·php
alexwang2114 小时前
HDU 4348 详细题解
c++·算法·题解·hdu·主席树·可持久化数据结构·可持久化线段树
程序员zgh4 小时前
C++ 拷贝赋值运算符 详解
c语言·开发语言·c++
念何架构之路5 小时前
restartmanager-重启管理子系统
java·开发语言