C++ 设计模式-策略模式

news/2025/2/22 13:55:52/

支付策略

#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <ctime>// 基础策略接口
class PaymentStrategy {
public:virtual ~PaymentStrategy() = default;virtual std::string name() const = 0;virtual bool validate(double amount, const std::string& currency) const = 0;virtual void pay(double amount, const std::string& currency) const = 0;virtual double calculate_fee(double amount) const = 0;
};// 策略工厂系统
class StrategyFactory {
public:using StrategyCreator = std::function<std::unique_ptr<PaymentStrategy>()>;static StrategyFactory& instance() {static StrategyFactory instance;return instance;}void register_strategy(const std::string& id, StrategyCreator creator) {creators_[id] = creator;}std::unique_ptr<PaymentStrategy> create(const std::string& id) const {if (auto it = creators_.find(id); it != creators_.end()) {return it->second();}return nullptr;}std::vector<std::string> available_strategies() const {std::vector<std::string> names;for (const auto& [id, _] : creators_) {names.push_back(id);}return names;}private:std::unordered_map<std::string, StrategyCreator> creators_;
};// 自动注册宏
#define REGISTER_PAYMENT_STRATEGY(StrategyClass, strategy_id) \namespace { \struct AutoRegister_##StrategyClass { \AutoRegister_##StrategyClass() { \StrategyFactory::instance().register_strategy( \strategy_id, \[]{ return std::make_unique<StrategyClass>(); } \); \} \}; \AutoRegister_##StrategyClass auto_reg_##StrategyClass; \}// 微信支付策略
class WechatPayStrategy : public PaymentStrategy {const double max_amount_ = 50000.0; // 单笔最大金额public:std::string name() const override { return "WeChat Pay"; }bool validate(double amount, const std::string& currency) const override {return currency == "CNY" && amount <= max_amount_;}void pay(double amount, const std::string& currency) const override {std::cout << "微信支付成功\n"<< "金额: ¥" << amount << "\n"<< "请在小程序确认支付" << std::endl;}double calculate_fee(double amount) const override {return amount * 0.001; // 0.1%手续费}
};
REGISTER_PAYMENT_STRATEGY(WechatPayStrategy, "wechat_pay");// PayPal策略
class PayPalStrategy : public PaymentStrategy {const std::vector<std::string> supported_currencies_{"USD", "EUR", "GBP"};public:std::string name() const override { return "PayPal"; }bool validate(double amount, const std::string& currency) const override {return std::find(supported_currencies_.begin(), supported_currencies_.end(), currency) != supported_currencies_.end();}void pay(double amount, const std::string& currency) const override {std::cout << "Processing PayPal payment\n"<< "Amount: " << currency << " " << amount << "\n"<< "Redirecting to PayPal login..." << std::endl;}double calculate_fee(double amount) const override {return std::max(0.3, amount * 0.05); // 5% + $0.3}
};
REGISTER_PAYMENT_STRATEGY(PayPalStrategy, "paypal");// 比特币策略(带实时汇率)
class BitcoinStrategy : public PaymentStrategy {// 模拟实时汇率获取double get_bitcoin_price() const {static const double BASE_PRICE = 45000.0; // 基础价格// 模拟价格波动return BASE_PRICE * (1.0 + 0.1 * sin(time(nullptr) % 3600));}public:std::string name() const override { return "Bitcoin"; }bool validate(double amount, const std::string& currency) const override {return currency == "BTC" || currency == "USD";}void pay(double amount, const std::string& currency) const override {if (currency == "USD") {double btc_amount = amount / get_bitcoin_price();std::cout << "Converting USD to BTC: " << "₿" << btc_amount << std::endl;amount = btc_amount;}std::cout << "区块链交易确认中...\n"<< "转账金额: ₿" << amount << "\n"<< "预计确认时间: 10分钟" << std::endl;}double calculate_fee(double amount) const override {return 0.0001 * get_bitcoin_price(); // 固定矿工费}
};
REGISTER_PAYMENT_STRATEGY(BitcoinStrategy, "bitcoin");// 支付处理器
class PaymentProcessor {std::unordered_map<std::string, std::unique_ptr<PaymentStrategy>> strategies_;public:void load_strategy(const std::string& id) {if (auto strategy = StrategyFactory::instance().create(id)) {strategies_[id] = std::move(strategy);}}void process_payment(const std::string& currency, double amount) {auto strategy = select_strategy(currency, amount);if (!strategy) {throw std::runtime_error("No available payment method");}std::cout << "\n=== 支付方式: " << strategy->name() << " ==="<< "\n金额: " << currency << " " << amount<< "\n手续费: " << strategy->calculate_fee(amount)<< "\n-------------------------" << std::endl;strategy->pay(amount, currency);}private:PaymentStrategy* select_strategy(const std::string& currency, double amount) {// 选择优先级:本地支付 > 国际支付 > 加密货币for (auto& [id, strategy] : strategies_) {if (id == "wechat_pay" && strategy->validate(amount, currency)) {return strategy.get();}}for (auto& [id, strategy] : strategies_) {if (id == "alipay" && strategy->validate(amount, currency)) {return strategy.get();}}for (auto& [id, strategy] : strategies_) {if (strategy->validate(amount, currency)) {return strategy.get();}}return nullptr;}
};// 使用示例
int main() {PaymentProcessor processor;// 加载所有注册的支付方式for (const auto& id : StrategyFactory::instance().available_strategies()) {processor.load_strategy(id);}// 人民币支付try {processor.process_payment("CNY", 200.0);processor.process_payment("CNY", 60000.0); // 应触发异常} catch (const std::exception& e) {std::cerr << "支付失败: " << e.what() << std::endl;}// 美元支付processor.process_payment("USD", 500.0);// 比特币支付processor.process_payment("BTC", 0.1);processor.process_payment("USD", 1000.0); // 自动转换为BTCreturn 0;
}

代码解析

  1. 策略扩展机制
REGISTER_PAYMENT_STRATEGY(WechatPayStrategy, "wechat_pay");
  • 自动注册:通过宏实现新策略的零配置接入
  • 唯一标识:每个策略有唯一的注册ID(如wechat_pay)
  1. 微信支付实现
class WechatPayStrategy : public PaymentStrategy {bool validate(...) { /* 校验人民币 */ }void pay(...) { /* 微信特有流程 */ }
};
  • 本地化支持:仅接受人民币
  • 移动支付流程:模拟小程序支付场景
  1. PayPal国际支付
class PayPalStrategy : public PaymentStrategy {bool validate(...) { /* 支持多币种 */ }void pay(...) { /* 跳转PayPal */ }
};
  • 多币种支持:USD/EUR/GBP
  • 典型手续费模型:固定费用+百分比
  1. 比特币支付
class BitcoinStrategy : public PaymentStrategy {double get_bitcoin_price() { /* 模拟实时价格 */ }void pay(...) { /* 自动转换法币 */ }
};
  • 加密货币支持:直接接受BTC或自动转换USD
  • 动态手续费:基于当前币价计算矿工费
  1. 智能策略选择
PaymentStrategy* select_strategy(...) {// 优先选择本地支付方式// 次选国际支付// 最后考虑加密货币
}
  • 业务优先级:体现支付方式选择策略
  • 动态路由:根据金额和币种自动路由

执行结果示例

=== 支付方式: WeChat Pay ===
金额: CNY 200
手续费: 0.2
-------------------------
微信支付成功
金额: ¥200
请在小程序确认支付支付失败: No available payment method=== 支付方式: PayPal ===
金额: USD 500
手续费: 25.3
-------------------------
Processing PayPal payment
Amount: USD 500
Redirecting to PayPal login...=== 支付方式: Bitcoin ===
金额: BTC 0.1
手续费: 4.5
-------------------------
区块链交易确认中...
转账金额: ₿0.1
预计确认时间: 10分钟=== 支付方式: Bitcoin ===
金额: USD 1000
手续费: 4.5
-------------------------
Converting USD to BTC: ₿0.0221132
区块链交易确认中...
转账金额: ₿0.0221132
预计确认时间: 10分钟

待扩展

  1. 新增策略步骤

    • 继承PaymentStrategy实现新类
    • 实现所有纯虚函数
    • 使用REGISTER_PAYMENT_STRATEGY注册
  2. 动态配置

    // 示例:从JSON加载策略配置
    void load_config(const json& config) {for (auto& item : config["strategies"]) {auto strategy = factory.create(item["id"]);strategy->configure(item["params"]);add_strategy(std::move(strategy));}
    }
    
  3. 混合支付

    class SplitPaymentStrategy : public PaymentStrategy {// 支持多个策略分摊支付void pay(...) override {credit_card_->pay(part1, currency);crypto_->pay(part2, currency);}
    };

http://www.ppmy.cn/news/1574173.html

相关文章

泷羽Sec-蓝队基础之网络七层杀伤链

声明 学习视频来自B站UP主 泷羽sec,如涉及侵泷羽sec权马上删除文章笔记的只是方便各位师傅学习知识,以下网站涉及学习内容,其他的都与本人无关,切莫逾越法律红线,否则后果自负 一、企业管理技术 信息安全管理成熟度模型&#xff08;ISM3&#xff09;&#xff1a;描述了企业安…

大数据学习(49) - Flink按键分区状态(Keyed State)

&&大数据学习&& &#x1f525;系列专栏&#xff1a; &#x1f451;哲学语录: 承认自己的无知&#xff0c;乃是开启智慧的大门 &#x1f496;如果觉得博主的文章还不错的话&#xff0c;请点赞&#x1f44d;收藏⭐️留言&#x1f4dd;支持一下博主哦&#x1f91…

计算机三级网络技术知识汇总【4】

第四章 路由设计技术基础 1. IP路由选择 1.1 初识路由器 路由器&#xff08;Router&#xff09;是连接两个或多个网络的硬件设备&#xff0c;在网络间起网关的作用&#xff0c;是读取每一个数据包中的地址然后决定如何传送的专用智能性的网络设备。 1.2 分组转发 分组转发…

springboot三层架构详细讲解

目录 springBoot三层架构 0.简介1.各层架构 1.1 Controller层1.2 Service层1.3 ServiceImpl1.4 Mapper1.5 Entity1.6 Mapper.xml 2.各层之间的联系 2.1 Controller 与 Service2.2 Service 与 ServiceImpl2.3 Service 与 Mapper2.4 Mapper 与 Mapper.xml2.5 Service 与 Entity2…

深入探索 DeepSeek 在数据分析与可视化中的应用

在数据驱动的时代&#xff0c;快速且准确地分析和呈现数据对于企业和个人都至关重要。DeepSeek 作为一款先进的人工智能工具&#xff0c;凭借其强大的数据处理和可视化能力&#xff0c;正在革新数据分析的方式。 1. 数据预处理与清洗 在进行数据分析前&#xff0c;数据预处理…

Docker换源加速(更换镜像源)详细教程(2025.2最新可用镜像,全网最详细)

文章目录 前言可用镜像源汇总换源方法1-临时换源换源方法2-永久换源&#xff08;推荐&#xff09;常见问题及对应解决方案1.换源后&#xff0c;可以成功pull&#xff0c;但是search会出错 补充1.如何测试镜像源是否可用2.Docker内的Linux换源教程 换源速通版&#xff08;可以直…

AI知识库和全文检索的区别

1、AI知识库的作用 AI知识库是基于人工智能技术构建的智能系统&#xff0c;能够理解、推理和生成信息。它的核心作用包括&#xff1a; 1.1 语义理解 自然语言处理&#xff08;NLP&#xff09;&#xff1a;AI知识库能够理解用户查询的语义&#xff0c;而不仅仅是关键词匹配。 …

C语言 —— 浮生百态 生灭有时 - 数组

目录 1. 数组的概念 2. ⼀维数组的创建和初始化 2.1 数组创建 2.2 数组的初始化 2.3 数组的类型 3. ⼀维数组的使用 3.1 数组下标的访问 4. ⼀维数组在内存中的存储 5. ⼆维数组的概念 5.1 ⼆维数组的创建 5.2 ⼆维数组的初始化 6. ⼆维数组的使用 6.1 ⼆维数组的下…