跳转至

常用设计模式

// test.cpp
#include <atomic>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <memory>
#include <vector>

// 1. Observer Pattern - Market Data Publisher
class MarketDataObserver {
 public:
  virtual ~MarketDataObserver() = default;
  virtual void onUpdate(double price, int volume) = 0;
};

// Preallocated fixed-size observer list
template <size_t MAX_OBSERVERS = 64>
class LockFreeMarketDataPublisher {
 private:
  MarketDataObserver* observers_[MAX_OBSERVERS];
  std::atomic<uint32_t> count_{0};

 public:
  bool subscribe(MarketDataObserver* observer) {
    uint32_t current_count = count_.load(std::memory_order_acquire);
    if (current_count >= MAX_OBSERVERS) {
      return false;  // Capacity exceeded
    }

    if (!count_.compare_exchange_strong(current_count, current_count + 1,
                                        std::memory_order_acq_rel)) {
      return false;  // Concurrent modification
    }

    observers_[current_count] = observer;
    return true;
  }

  void notify(double price, int volume) {
    const uint32_t current_count = count_.load(std::memory_order_acquire);
    for (uint32_t i = 0; i < current_count; ++i) {
      observers_[i]->onUpdate(price, volume);
    }
  }
};

// 2. Factory Pattern - Order Creation and Destruction
enum class OrderType : uint8_t { MARKET, LIMIT, STOP };

class alignas(64) Order {
 public:
  virtual ~Order() = default;
  virtual void execute() = 0;
};

class alignas(64) MarketOrder : public Order {
 public:
  void execute() override {
    // execute market order logic here
  }
};

class alignas(64) LimitOrder : public Order {
 public:
  void execute() override {
    // execute limit order logic here
  }
};

class alignas(64) StopOrder : public Order {
 public:
  void execute() override {
    // Stop order logic would go here
  }
};

class OrderFactory {
 public:
  static Order* createOrder(OrderType type) {
    switch (type) {
      case OrderType::MARKET:
        return new MarketOrder();
      case OrderType::LIMIT:
        return new LimitOrder();
      case OrderType::STOP:
        return new StopOrder();
      default:
        return nullptr;
    }
  }

  static void destroyOrder(Order* order) { delete order; }
};

// 3. Singleton Pattern - Global Configuration Manager
class ConfigManager {
 private:
  static std::atomic<ConfigManager*> instance_;

  alignas(64) std::atomic<double> maxPositionSize{1000000.0};
  alignas(64) std::atomic<int32_t> maxOrderCount{1000};
  alignas(64) std::atomic<bool> riskCheckEnabled{true};

  ConfigManager() = default;

 public:
  static ConfigManager* getInstance() {
    ConfigManager* tmp = instance_.load(std::memory_order_acquire);
    if (tmp == nullptr) {
      tmp = new ConfigManager();
      instance_.store(tmp, std::memory_order_release);
    }
    return tmp;
  }

  double getMaxPositionSize() const {
    return maxPositionSize.load(std::memory_order_relaxed);
  }

  void setMaxPositionSize(double size) {
    maxPositionSize.store(size, std::memory_order_relaxed);
  }

  int32_t getMaxOrderCount() const {
    return maxOrderCount.load(std::memory_order_relaxed);
  }

  void setMaxOrderCount(int32_t count) {
    maxOrderCount.store(count, std::memory_order_relaxed);
  }

  bool isRiskCheckEnabled() const {
    return riskCheckEnabled.load(std::memory_order_relaxed);
  }

  void setRiskCheckEnabled(bool enabled) {
    riskCheckEnabled.store(enabled, std::memory_order_relaxed);
  }
};

std::atomic<ConfigManager*> ConfigManager::instance_{nullptr};

// 4. Strategy Pattern - Trading Strategy
class TradingContext {
 public:
  using TradeFunction = void (*)(double);

 private:
  TradeFunction tradeFunc_ = nullptr;

 public:
  template <typename Strategy>
  void setStrategy() {
    tradeFunc_ = [](double price) { Strategy::trade(price); };
  }

  void executeStrategy(double marketPrice) const {
    if (tradeFunc_) {
      tradeFunc_(marketPrice);
    }
  }
};

struct MarketMakingStrategy {
  static void trade(double marketPrice) {
    // trading logic would go here
  }
};

struct ArbitrageStrategy {
  static void trade(double marketPrice) {
    // trading logic would go here
  }
};

struct TrendFollowingStrategy {
  static void trade(double marketPrice) {
    // trading logic would go here
  }
};

// 5. State Pattern - Order Lifecycle Management
enum class OrderState : uint8_t {
  NEW = 0,
  PARTIALLY_FILLED = 1,
  FILLED = 2,
  CANCELLED = 3,
  REJECTED = 4
};

// Cache-aligned state transition table for maximum performance
alignas(64) constexpr OrderState TRANSITION_TABLE[5][4] = {
    // NEW -> [PARTIAL_FILL, FULL_FILL, CANCEL, REJECT]
    {OrderState::PARTIALLY_FILLED, OrderState::FILLED, OrderState::CANCELLED,
     OrderState::REJECTED},

    // PARTIALLY_FILLED -> [PARTIAL_FILL, FULL_FILL, CANCEL, REJECT]
    {OrderState::PARTIALLY_FILLED, OrderState::FILLED, OrderState::CANCELLED,
     OrderState::REJECTED},

    // FILLED (terminal state)
    {OrderState::FILLED, OrderState::FILLED, OrderState::FILLED,
     OrderState::FILLED},

    // CANCELLED (terminal state)
    {OrderState::CANCELLED, OrderState::CANCELLED, OrderState::CANCELLED,
     OrderState::CANCELLED},

    // REJECTED (terminal state)
    {OrderState::REJECTED, OrderState::REJECTED, OrderState::REJECTED,
     OrderState::REJECTED}};

class alignas(64) OrderStateMachine {
 private:
  std::atomic<OrderState> state_{OrderState::NEW};

 public:
  OrderState getState() const { return state_.load(std::memory_order_relaxed); }

  // state transitions with cache-friendly lookup
  bool processPartialFill() {
    OrderState current = state_.load(std::memory_order_acquire);
    if (current == OrderState::FILLED || current == OrderState::CANCELLED ||
        current == OrderState::REJECTED) {
      return false;  // Terminal state, no transitions allowed
    }

    OrderState next = TRANSITION_TABLE[static_cast<uint8_t>(current)][0];
    state_.store(next, std::memory_order_release);
    return true;
  }

  bool processFullFill() {
    OrderState current = state_.load(std::memory_order_acquire);
    if (current == OrderState::FILLED || current == OrderState::CANCELLED ||
        current == OrderState::REJECTED) {
      return false;
    }

    OrderState next = TRANSITION_TABLE[static_cast<uint8_t>(current)][1];
    state_.store(next, std::memory_order_release);
    return true;
  }

  bool processCancel() {
    OrderState current = state_.load(std::memory_order_acquire);
    if (current == OrderState::FILLED || current == OrderState::CANCELLED ||
        current == OrderState::REJECTED) {
      return false;
    }

    OrderState next = TRANSITION_TABLE[static_cast<uint8_t>(current)][2];
    state_.store(next, std::memory_order_release);
    return true;
  }

  bool processReject() {
    OrderState current = state_.load(std::memory_order_acquire);
    if (current == OrderState::FILLED || current == OrderState::CANCELLED ||
        current == OrderState::REJECTED) {
      return false;
    }

    OrderState next = TRANSITION_TABLE[static_cast<uint8_t>(current)][3];
    state_.store(next, std::memory_order_release);
    return true;
  }

  // Check if order is in a terminal state
  bool isTerminal() const {
    OrderState current = state_.load(std::memory_order_relaxed);
    return (current == OrderState::FILLED || current == OrderState::CANCELLED ||
            current == OrderState::REJECTED);
  }
};

int main() {
  // Observer Pattern Example
  LockFreeMarketDataPublisher<> publisher;

  class FixedObserver : public MarketDataObserver {
   public:
    void onUpdate(double price, int volume) override {
      // Fast inline processing without system calls
      // In real system, this would contain actual processing logic
    }
  };

  FixedObserver observer;
  publisher.subscribe(&observer);
  publisher.notify(100.5, 50);

  // Factory Pattern Example
  Order* order = OrderFactory::createOrder(OrderType::LIMIT);
  order->execute();
  OrderFactory::destroyOrder(order);

  // Singleton Pattern Example
  ConfigManager* config = ConfigManager::getInstance();
  double maxSize = config->getMaxPositionSize();

  // Strategy Pattern Example
  TradingContext context;
  context.setStrategy<MarketMakingStrategy>();
  context.executeStrategy(100.5);

  // State Pattern Example
  OrderStateMachine orderState;
  orderState.processPartialFill();  // NEW -> PARTIALLY_FILLED
  orderState.processFullFill();     // PARTIALLY_FILLED -> FILLED

  return 0;
}