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

支付策略

#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.rhkb.cn/news/22530.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机视觉:主流数据集整理

第一章&#xff1a;计算机视觉中图像的基础认知 第二章&#xff1a;计算机视觉&#xff1a;卷积神经网络(CNN)基本概念(一) 第三章&#xff1a;计算机视觉&#xff1a;卷积神经网络(CNN)基本概念(二) 第四章&#xff1a;搭建一个经典的LeNet5神经网络(附代码) 第五章&#xff1…

二级公共基础之数据结构与算法篇(五)树和二叉树

目录 前言 一、树的基本概念 1.父结点和根节点 2.子节点和叶子节点 3.度和深度 4.子树 二、二叉树及其基本性质 1. 二叉树的定义 2. 二叉树的基本性质 性质1 性质2 性质3 性质4 性质5 性质6 三、二叉树的存储结构 四、二叉树的遍历 1.遍历二叉树的概念 1. 前…

自制操作系统学习第七天

今天要做什么&#xff1f; 实现HLT&#xff0c;不让计算机处于HALT&#xff08;HLT&#xff09;.用C语言实现内存写入&#xff08;错误&#xff0c;需要分析&#xff09; 一:使用HLT&#xff0c;让计算机处于睡眠状态 写了下面这个程序&#xff0c;naskfunc.nas 函数名叫io_h…

Python Django系列—入门实例(二)

数据库配置 现在&#xff0c;打开 mysite/settings.py 。这是个包含了 Django 项目设置的 Python 模块。 默认情况下&#xff0c;​ DATABASES 配置使用 SQLite。如果你是数据库新手&#xff0c;或者只是想尝试 Django&#xff0c;这是最简单的选择。SQLite 包含在 Python 中…

DeepSeek接入Siri(已升级支持苹果手表)完整版硅基流动DeepSeek-R1部署

DeepSeek接入Siri&#xff08;已升级支持苹果手表&#xff09;完整版硅基流动DeepSeek-R1部署 **DeepSeek** 是一款专注于深度学习和人工智能的工具或平台&#xff0c;通常与人工智能、机器学习、自动化分析等领域有关。它的主要功能可能包括&#xff1a;深度学习模型搜索&…

抗辐照加固CAN FD芯片的商业航天与车规级应用解析

在工业自动化、智能汽车、航空航天及国防装备等关键领域&#xff0c;数据传输的安全性、可靠性与极端环境适应能力是技术升级的核心挑战。国科安芯推出全新一代CANFD&#xff08;Controller Area Network Flexible Data Rate&#xff09;芯片&#xff0c;以高安全、高可靠、断电…

Java数据结构第十二期:走进二叉树的奇妙世界(一)

专栏&#xff1a;数据结构(Java版) 个人主页&#xff1a;手握风云 目录 一、树型结构 1.1. 树的定义 1.2. 树的基本概念 1.3. 树的表示形式 二、二叉树 2.1. 概念 2.2. 两种特殊的二叉树 2.3. 二叉树的性质 2.4. 二叉树的存储 三、二叉树的基本操作 一、树型结构 1.…

nginx 反向代理 配置请求路由

nginx | 反向代理 | 配置请求路由 nginx简介 Nginx&#xff08;发音为“Engine-X”&#xff09;是一款高性能、开源的 Web 服务器和反向代理服务器&#xff0c;同时也支持邮件代理和负载均衡等功能。它由俄罗斯程序员伊戈尔西索夫&#xff08;Igor Sysoev&#xff09;于 2004…

ath9k(Atheros芯片)开源驱动之wifi连接

为什么会推荐这个wifi 驱动进行学习&#xff1f; ath9k&#xff08;Atheros芯片&#xff09;&#xff1a;代码结构清晰&#xff0c;适合学习实践 为什么我只在开篇写了一个wifi连接的操作&#xff1f; 先让一个开源驱动在你的硬件上跑起来&#xff0c;再逐步修改&#xff0c…

LLaMA-Factory|微调大语言模型初探索(4),64G显存微调13b模型

上篇文章记录了使用lora微调deepseek-7b&#xff0c;微调成功&#xff0c;但是微调llama3-8b显存爆炸&#xff0c;这次尝试使用qlora微调HQQ方式量化&#xff0c;微调更大参数体量的大语言模型&#xff0c;记录下来微调过程&#xff0c;仅供参考。 对过程不感兴趣的兄弟们可以直…

知识管理平台如何实现高效数据整合?

内容概要 现代知识管理平台通过架构化的四库体系&#xff08;资源库、规则库、模型库、知识库&#xff09;驱动数据智能整合进程。核心机制依托智能数据工具集对异构数据进行自动化清洗与语义标注&#xff0c;其跨源数据汇聚能力支持超过200种结构化与非结构化数据源的接入&am…

近10年气象分析(深度学习)

这是一个气象数据分析程序&#xff0c;主要用于分析和可视化气象数据。以下是该文件的主要功能&#xff1a; 1. 数据加载 在线数据&#xff1a;尝试从 GitHub 加载气象数据。 示例数据&#xff1a;如果无法加载在线数据&#xff0c;程序会自动生成示例数据。 2. 数据分析 …

DeepSeek最新开源动态:核心技术公布

2月21日午间&#xff0c;DeepSeek在社交平台X发文称&#xff0c;从下周开始&#xff0c;他们将开源5个代码库&#xff0c;以完全透明的方式与全球开发者社区分享他们的研究进展。并将这一计划定义为“Open Source Week”。 DeepSeek表示&#xff0c;即将开源的代码库是他们在线…

wps中zotero插件消失,解决每次都需要重新开问题

参考 查看zotero目录 D:\zotero\integration\word-for-windows 加载项点击 dotm即可 长期解决 把dom 复制到 C:\Users\89735\AppData\Roaming\kingsoft\office6\templates\wps\zh_CN还是每次都需要重新开的话 重新加载一下

洛谷B3629

B3629 吃冰棍 - 洛谷 代码区&#xff1a; #include<algorithm> #include<iostream>using namespace std; int main(){int n,ans;cin >> n;for(int in/2;i<n;i){int ti;ans0;while(t>3){t-3;ans3;t;}if(anst>n){cout << i;return 0;}}return…

VMware安装Centos 9虚拟机+设置共享文件夹+远程登录

一、安装背景 工作需要安装一台CentOS-Stream-9的机器环境&#xff0c;所以一开始的安装准备工作有&#xff1a; vmware版本&#xff1a;VMware Workstation 16 镜像版本&#xff1a;CentOS-Stream-9-latest-x86_64-dvd1.iso &#xff08;kernel-5.14.0&#xff09; …

[ProtoBuf] 介绍 | 保姆级win/linux安装教程

目录 一、序列化概念 二、ProtoBuf 是什么 三、ProtoBuf 的使用特点 ProtoBuf 在不同操作系统下的安装 一、ProtoBuf 在 Windows 下的安装 二、ProtoBuf 在 Linux 下的安装 三、检查是否安装成功 安装教程 可以直接目录跳转到后面 笔记参考&#xff1a;官方文档 一、序…

element ui的select选择框

我们首先先试一下&#xff0c;这个东西怎么玩的 <el-select v-model"select" change"changeSelect"><el-option value"香蕉"></el-option><el-option value"菠萝"></el-option><el-option value&quo…

51单片机学习之旅——定时器

打开软件 1与其它等于其它&#xff0c;0与其它等于0 1或其它等于1&#xff0c;0或其它等于其它 TMODTMOD&0xF0;//0xF01111 0000进行与操作&#xff0c;高四位保持&#xff0c;低四位清零&#xff0c;高四位定时器1&#xff0c;低四位定时器0 TMODTMOD|0x01;//0x010000 0…

【跟我学YOLO】(1)YOLO12:以注意力为中心的物体检测

欢迎关注『跟我学 YOLO』系列 【跟我学YOLO】&#xff08;1&#xff09;YOLO12&#xff1a;以注意力为中心的物体检测] 0. YOLOv12 简介0.1 YOLO12 论文下载0.2 YOLO12 的主要改进0.3 YOLO12 支持的任务和性能0.4 论文摘要 1. 背景介绍2. 相关的工作3. 方法3.1 效率分析3.2 区域…