【C++】状态模式

发布于:2025-07-04 ⋅ 阅读:(22) ⋅ 点赞:(0)

状态模式(State Pattern)是一种【行为型】设计模式,它允许对象在其内部状态发生变化时改变其行为,看起来就像该对象改变了它的类一样。这种模式将状态相关的行为封装在独立的状态类中,并将状态转换逻辑集中管理,使系统更易于维护和扩展。

一、模式核心概念与结构

状态模式包含三个核心角色:

  1. 上下文(Context):定义客户端感兴趣的接口,维护一个当前状态的引用。
  2. 状态接口(State):定义特定状态下的行为接口,所有具体状态类必须实现该接口。
  3. 具体状态(Concrete State):实现状态接口,封装与特定状态相关的行为,并负责状态转换。

二、C++ 实现示例:自动售货机状态管理

以下是一个自动售货机的示例,演示如何使用状态模式管理不同状态下的行为:

#include <iostream>
#include <string>
#include <memory>

// 前向声明
class VendingMachine;

// 状态接口
class State {
   
public:
    virtual ~State() = default;
    virtual void insertMoney(VendingMachine* machine, double amount) = 0;
    virtual void selectProduct(VendingMachine* machine, const std::string& product) = 0;
    virtual void dispense(VendingMachine* machine) = 0;
    virtual void cancel(VendingMachine* machine) = 0;
    virtual std::string getStateName() const = 0;
};

// 上下文:自动售货机
class VendingMachine {
   
private:
    std::shared_ptr<State> currentState;
    double balance;
    std::string selectedProduct;
    double productPrice;

public:
    VendingMachine();
    
    void setState(std::shared_ptr<State> state) {
   
        currentState = state;
        std::cout << "State changed to: " << currentState->getStateName() << std::endl;
    }
    
    void insertMoney(double amount) {
   
        currentState->insertMoney(this, amount);
    }
    
    void selectProduct(const std::string& product) {
   
        currentState->selectProduct(this, product);
    }
    
    void dispense() {
   
        currentState->dispense(this);
    }
    
    void cancel() {
   
        currentState->cancel(this);
    }
    
    double getBalance() const {
    return balance; }
    void setBalance(double amount) {
    balance = amount; }
    
    std::string getSelectedProduct() const {
    return selectedProduct; }
    void setSelectedProduct(const std::string& product) {
    selectedProduct = product; }
    
    double getProductPrice() const {
    return productPrice; }
    void setProductPrice(double price) {
    productPrice = price; }
};

// 具体状态:待机状态
class IdleState : public State {
   
public:
    void insertMoney(VendingMachine* machine, double amount) override {
   
        machine->setBalance(amount);
        std::cout << "Money inserted: " << amount << std::endl;
        machine->setState