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

支付策略

cpp 复制代码
#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); // 自动转换为BTC

    return 0;
}

代码解析

  1. 策略扩展机制
cpp 复制代码
REGISTER_PAYMENT_STRATEGY(WechatPayStrategy, "wechat_pay");
  • 自动注册:通过宏实现新策略的零配置接入
  • 唯一标识:每个策略有唯一的注册ID(如wechat_pay)
  1. 微信支付实现
cpp 复制代码
class WechatPayStrategy : public PaymentStrategy {
    bool validate(...) { /* 校验人民币 */ }
    void pay(...) { /* 微信特有流程 */ }
};
  • 本地化支持:仅接受人民币
  • 移动支付流程:模拟小程序支付场景
  1. PayPal国际支付
cpp 复制代码
class PayPalStrategy : public PaymentStrategy {
    bool validate(...) { /* 支持多币种 */ }
    void pay(...) { /* 跳转PayPal */ }
};
  • 多币种支持:USD/EUR/GBP
  • 典型手续费模型:固定费用+百分比
  1. 比特币支付
cpp 复制代码
class BitcoinStrategy : public PaymentStrategy {
    double get_bitcoin_price() { /* 模拟实时价格 */ }
    void pay(...) { /* 自动转换法币 */ }
};
  • 加密货币支持:直接接受BTC或自动转换USD
  • 动态手续费:基于当前币价计算矿工费
  1. 智能策略选择
cpp 复制代码
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. 动态配置

    cpp 复制代码
    // 示例:从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. 混合支付

    cpp 复制代码
    class SplitPaymentStrategy : public PaymentStrategy {
        // 支持多个策略分摊支付
        void pay(...) override {
            credit_card_->pay(part1, currency);
            crypto_->pay(part2, currency);
        }
    };
相关推荐
JANGHIGH8 分钟前
c++ std::list使用笔记
c++·笔记·list
画个逗号给明天"15 分钟前
C++STL容器之list
开发语言·c++
Lqingyyyy2 小时前
P2865 [USACO06NOV] Roadblocks G 与最短路的路径可重复的严格次短路
开发语言·c++·算法
C语言小火车2 小时前
深入解析C++26 Execution Domain:设计原理与实战应用
java·开发语言·c++·异构计算调度·c++26执行模型·domain定制
ox00803 小时前
C++ 设计模式-中介者模式
c++·设计模式·中介者模式
黄铎彦3 小时前
使用GDI+、文件和目录和打印API,批量将图片按文件名分组打包成PDF
c++·windows·pdf
Ciderw3 小时前
LLVM编译器简介
c++·golang·编译·编译器·gcc·llvm·基础设施
扣丁梦想家4 小时前
设计模式教程:中介者模式(Mediator Pattern)
设计模式·中介者模式
花王江不语4 小时前
设计模式学习笔记
笔记·学习·设计模式
和光同尘@4 小时前
74. 搜索二维矩阵(LeetCode 热题 100)
数据结构·c++·线性代数·算法·leetcode·职场和发展·矩阵