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