第十九章:千变万化,随心而动——State的状态艺术

第十九章:千变万化,随心而动------State的状态艺术

风云再起,状态大师登场

在Chain of Responsibility展示完他们精妙的责任链艺术后,State表情和气质瞬息万变的怪杰走出。他的形态在众人眼前不断变换,时而如烈火般炽热,时而如寒冰般冷静,仿佛能够随心所欲地改变自身状态。

"Chain of Responsibility兄的请求传递确实精妙,"State变化多端地说道,"但在对象状态变化和行为切换方面,需要更加灵活的状态管理方式。诸位请看------"

State的身形在几种截然不同的状态间快速切换:"我的状态模式,专为解决对象状态变化时的行为改变问题而生!我允许对象在内部状态改变时改变它的行为,对象看起来就像改变了它的类!"

架构老人眼中闪过赞许之色:"善!State,就请你为大家展示这状态艺术的精妙所在。"

状态模式的核心要义

State面向众人,开始阐述他的武学真谛:

"在我的状态模式中,主要包含三个核心角色:"

"Context(上下文):维护一个ConcreteState子类的实例,这个实例定义当前状态。"

"State(状态):定义一个接口以封装与Context的一个特定状态相关的行为。"

"ConcreteState(具体状态):每一个子类实现一个与Context的一个状态相关的行为。"

"其精妙之处在于,"State继续道,"我将与特定状态相关的行为局部化,并且将不同状态的行为分割开来。通过将状态转换规则分布到State子类之间,来减少条件判断语句的复杂性!"

C++实战:智能交通灯系统

"且让我以一个智能交通灯系统为例,展示状态模式的实战应用。"State说着,手中凝聚出一道道代码流光。

基础框架搭建

首先,State定义了交通灯状态接口:

cpp 复制代码
#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
#include <map>
#include <iomanip>
#include <sstream>
#include <random>
#include <thread>
#include <chrono>
#include <functional>

// 前向声明
class TrafficLight;

// 状态接口
class TrafficLightState {
public:
    virtual ~TrafficLightState() = default;
    
    // 状态行为
    virtual void handle(TrafficLight* context) = 0;
    
    // 状态信息
    virtual std::string getName() const = 0;
    virtual std::string getColor() const = 0;
    virtual int getDuration() const = 0;
    
    // 状态转换
    virtual std::string getNextState() const = 0;
    
    // 状态特性
    virtual bool canVehiclesGo() const = 0;
    virtual bool canPedestriansCross() const = 0;
    virtual bool isTransitional() const = 0;
    
    // 状态描述
    virtual std::string getDescription() const {
        std::stringstream ss;
        ss << getName() << " [" << getColor() << ", " << getDuration() << "s, "
           << "车辆:" << (canVehiclesGo() ? "通行" : "停止") << ", "
           << "行人:" << (canPedestriansCross() ? "通行" : "等待") << "]";
        return ss.str();
    }
};

// 上下文:交通灯
class TrafficLight {
private:
    std::unique_ptr<TrafficLightState> currentState_;
    std::string lightId_;
    int operationCount_;
    std::chrono::system_clock::time_point startTime_;
    std::vector<std::string> stateHistory_;
    
public:
    TrafficLight(const std::string& id) 
        : lightId_(id), operationCount_(0) {
        std::cout << "🚦 创建交通灯: " << lightId_ << std::endl;
        startTime_ = std::chrono::system_clock::now();
    }
    
    ~TrafficLight() {
        std::cout << "🗑️  销毁交通灯: " << lightId_ << std::endl;
    }
    
    // 设置状态
    void setState(std::unique_ptr<TrafficLightState> state) {
        std::string oldStateName = currentState_ ? currentState_->getName() : "无";
        std::string newStateName = state->getName();
        
        currentState_ = std::move(state);
        operationCount_++;
        
        // 记录状态历史
        stateHistory_.push_back(newStateName);
        
        std::cout << "🔄 " << lightId_ << " 状态变更: " << oldStateName 
                  << " → " << newStateName << std::endl;
        std::cout << "   💡 " << currentState_->getDescription() << std::endl;
    }
    
    // 处理状态
    void operate() {
        if (!currentState_) {
            std::cout << "❌ " << lightId_ << " 未设置初始状态" << std::endl;
            return;
        }
        
        std::cout << "\n🎯 " << lightId_ << " 执行操作..." << std::endl;
        std::cout << "   当前状态: " << currentState_->getDescription() << std::endl;
        
        auto startTime = std::chrono::high_resolution_clock::now();
        currentState_->handle(this);
        auto endTime = std::chrono::high_resolution_clock::now();
        
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
        std::cout << "   ⏱️  操作耗时: " << duration.count() << "ms" << std::endl;
    }
    
    // 获取状态信息
    std::string getCurrentStateInfo() const {
        if (!currentState_) {
            return "无状态";
        }
        return currentState_->getDescription();
    }
    
    std::string getLightId() const { return lightId_; }
    int getOperationCount() const { return operationCount_; }
    
    // 显示状态历史
    void showStateHistory(int maxEntries = 10) const {
        int start = std::max(0, static_cast<int>(stateHistory_.size()) - maxEntries);
        std::cout << "\n📜 " << lightId_ << " 状态历史 (最近" << (stateHistory_.size() - start) << "个):" << std::endl;
        for (int i = start; i < stateHistory_.size(); ++i) {
            std::cout << "   " << (i + 1) << ". " << stateHistory_[i] << std::endl;
        }
    }
    
    // 获取运行时间
    std::string getUptime() const {
        auto now = std::chrono::system_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - startTime_);
        
        int hours = duration.count() / 3600;
        int minutes = (duration.count() % 3600) / 60;
        int seconds = duration.count() % 60;
        
        std::stringstream ss;
        ss << hours << "h " << minutes << "m " << seconds << "s";
        return ss.str();
    }
};

具体状态实现

State展示了各种交通灯状态的具体实现:

cpp 复制代码
// 具体状态:红灯状态
class RedLightState : public TrafficLightState {
private:
    int duration_;
    
public:
    RedLightState(int duration = 30) : duration_(duration) {
        std::cout << "   🔴 创建红灯状态,持续时间: " << duration_ << "s" << std::endl;
    }
    
    void handle(TrafficLight* context) override {
        std::cout << "   🛑 红灯状态处理..." << std::endl;
        std::cout << "      ● 所有车辆停止" << std::endl;
        std::cout << "      ● 行人可以通行" << std::endl;
        std::cout << "      ● 等待 " << duration_ << " 秒" << std::endl;
        
        // 模拟状态持续时间
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        
        std::cout << "      ⏰ 红灯时间结束,准备切换到下一状态" << std::endl;
    }
    
    std::string getName() const override { return "红灯"; }
    std::string getColor() const override { return "红色"; }
    int getDuration() const override { return duration_; }
    std::string getNextState() const override { return "绿灯"; }
    
    bool canVehiclesGo() const override { return false; }
    bool canPedestriansCross() const override { return true; }
    bool isTransitional() const override { return false; }
    
    void setDuration(int duration) {
        duration_ = duration;
        std::cout << "   ⏱️  设置红灯持续时间: " << duration_ << "s" << std::endl;
    }
};

// 具体状态:绿灯状态
class GreenLightState : public TrafficLightState {
private:
    int duration_;
    int vehicleCount_;
    
public:
    GreenLightState(int duration = 45, int vehicleCount = 0) 
        : duration_(duration), vehicleCount_(vehicleCount) {
        std::cout << "   🟢 创建绿灯状态,持续时间: " << duration_ << "s" << std::endl;
    }
    
    void handle(TrafficLight* context) override {
        std::cout << "   🚗 绿灯状态处理..." << std::endl;
        std::cout << "      ● 车辆可以通行" << std::endl;
        std::cout << "      ● 行人禁止通行" << std::endl;
        std::cout << "      ● 预计通过车辆: " << vehicleCount_ << " 辆" << std::endl;
        std::cout << "      ● 持续 " << duration_ << " 秒" << std::endl;
        
        // 模拟车辆通过
        if (vehicleCount_ > 0) {
            std::cout << "      🚙 车辆正在通过..." << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(600));
        } else {
            std::this_thread::sleep_for(std::chrono::milliseconds(400));
        }
        
        std::cout << "      ⏰ 绿灯时间结束,准备切换到下一状态" << std::endl;
    }
    
    std::string getName() const override { return "绿灯"; }
    std::string getColor() const override { return "绿色"; }
    int getDuration() const override { return duration_; }
    std::string getNextState() const override { return "黄灯"; }
    
    bool canVehiclesGo() const override { return true; }
    bool canPedestriansCross() const override { return false; }
    bool isTransitional() const override { return false; }
    
    void setVehicleCount(int count) {
        vehicleCount_ = count;
        std::cout << "   🚗 设置预计车辆数: " << vehicleCount_ << std::endl;
    }
};

// 具体状态:黄灯状态
class YellowLightState : public TrafficLightState {
private:
    int duration_;
    bool isWarning_;
    
public:
    YellowLightState(int duration = 5, bool isWarning = false) 
        : duration_(duration), isWarning_(isWarning) {
        std::cout << "   🟡 创建黄灯状态,持续时间: " << duration_ << "s" << std::endl;
    }
    
    void handle(TrafficLight* context) override {
        std::cout << "   ⚠️  黄灯状态处理..." << std::endl;
        
        if (isWarning_) {
            std::cout << "      ● 警告状态:所有方向注意" << std::endl;
            std::cout << "      ● 车辆准备停止" << std::endl;
            std::cout << "      ● 行人准备等待" << std::endl;
        } else {
            std::cout << "      ● 过渡状态:准备切换" << std::endl;
            std::cout << "      ● 已过停止线车辆可继续" << std::endl;
            std::cout << "      ● 行人等待" << std::endl;
        }
        
        std::cout << "      ● 持续 " << duration_ << " 秒" << std::endl;
        
        // 模拟过渡时间
        std::this_thread::sleep_for(std::chrono::milliseconds(300));
        
        std::cout << "      ⏰ 黄灯时间结束,准备切换到下一状态" << std::endl;
    }
    
    std::string getName() const override { return "黄灯"; }
    std::string getColor() const override { return "黄色"; }
    int getDuration() const override { return duration_; }
    std::string getNextState() const override { return isWarning_ ? "红灯" : "红灯"; }
    
    bool canVehiclesGo() const override { return false; }
    bool canPedestriansCross() const override { return false; }
    bool isTransitional() const override { return true; }
    
    void setWarningMode(bool warning) {
        isWarning_ = warning;
        std::cout << "   ⚠️  设置黄灯模式: " << (isWarning_ ? "警告" : "过渡") << std::endl;
    }
};

// 具体状态:全红状态(特殊状态)
class AllRedState : public TrafficLightState {
private:
    int duration_;
    std::string reason_;
    
public:
    AllRedState(int duration = 10, const std::string& reason = "紧急情况") 
        : duration_(duration), reason_(reason) {
        std::cout << "   🔴 创建全红状态,原因: " << reason_ << std::endl;
    }
    
    void handle(TrafficLight* context) override {
        std::cout << "   🚨 全红状态处理..." << std::endl;
        std::cout << "      ● 原因: " << reason_ << std::endl;
        std::cout << "      ● 所有方向停止" << std::endl;
        std::cout << "      ● 紧急车辆优先" << std::endl;
        std::cout << "      ● 持续 " << duration_ << " 秒" << std::endl;
        
        // 模拟紧急情况处理
        std::this_thread::sleep_for(std::chrono::milliseconds(700));
        
        std::cout << "      ⏰ 全红状态结束,恢复正常运行" << std::endl;
    }
    
    std::string getName() const override { return "全红"; }
    std::string getColor() const override { return "全红"; }
    int getDuration() const override { return duration_; }
    std::string getNextState() const override { return "红灯"; }
    
    bool canVehiclesGo() const override { return false; }
    bool canPedestriansCross() const override { return false; }
    bool isTransitional() const override { return true; }
    
    void setReason(const std::string& reason) {
        reason_ = reason;
        std::cout << "   🚨 设置全红原因: " << reason_ << std::endl;
    }
};

// 具体状态:闪烁黄灯状态(夜间模式)
class BlinkingYellowState : public TrafficLightState {
private:
    int blinkCount_;
    
public:
    BlinkingYellowState(int blinkCount = 10) : blinkCount_(blinkCount) {
        std::cout << "   💛 创建闪烁黄灯状态" << std::endl;
    }
    
    void handle(TrafficLight* context) override {
        std::cout << "   💛 闪烁黄灯状态处理..." << std::endl;
        std::cout << "      ● 夜间模式运行" << std::endl;
        std::cout << "      ● 车辆注意通行" << std::endl;
        std::cout << "      ● 行人注意安全" << std::endl;
        std::cout << "      ● 闪烁 " << blinkCount_ << " 次" << std::endl;
        
        // 模拟闪烁
        for (int i = 0; i < blinkCount_; ++i) {
            std::cout << "      ✨ 闪烁 " << (i + 1) << "/" << blinkCount_ << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(200));
        }
        
        std::cout << "      🌙 闪烁结束,继续夜间模式" << std::endl;
    }
    
    std::string getName() const override { return "闪烁黄灯"; }
    std::string getColor() const override { return "闪烁黄"; }
    int getDuration() const override { return blinkCount_ * 2; }
    std::string getNextState() const override { return "闪烁黄灯"; } // 循环
    
    bool canVehiclesGo() const override { return true; }
    bool canPedestriansCross() const override { return true; }
    bool isTransitional() const override { return false; }
    
    void setBlinkCount(int count) {
        blinkCount_ = count;
        std::cout << "   💛 设置闪烁次数: " << blinkCount_ << std::endl;
    }
};

UML 武功秘籍图

has-a <<interface>> TrafficLightState +handle(TrafficLight*) : void +getName() : string +getColor() : string +getDuration() : int +getNextState() : string +canVehiclesGo() : bool +canPedestriansCross() : bool +isTransitional() : bool +getDescription() : string TrafficLight -unique_ptr<TrafficLightState> currentState_ -string lightId_ -int operationCount_ -time_point startTime_ -vector<string> stateHistory_ +setState(unique_ptr<TrafficLightState>) : void +operate() : void +getCurrentStateInfo() : string +showStateHistory(int) : void +getUptime() : string RedLightState -int duration_ +handle(TrafficLight*) : void +getName() : string +getColor() : string +getDuration() : int +getNextState() : string +canVehiclesGo() : bool +canPedestriansCross() : bool +isTransitional() : bool +setDuration(int) : void GreenLightState -int duration_ -int vehicleCount_ +handle(TrafficLight*) : void +getName() : string +getColor() : string +getDuration() : int +getNextState() : string +canVehiclesGo() : bool +canPedestriansCross() : bool +isTransitional() : bool +setVehicleCount(int) : void YellowLightState -int duration_ -bool isWarning_ +handle(TrafficLight*) : void +getName() : string +getColor() : string +getDuration() : int +getNextState() : string +canVehiclesGo() : bool +canPedestriansCross() : bool +isTransitional() : bool +setWarningMode(bool) : void

实战演练:高级状态系统

State继续展示更复杂的状态模式应用:

cpp 复制代码
// 状态管理器:管理状态转换
class TrafficLightStateManager {
private:
    std::map<std::string, std::function<std::unique_ptr<TrafficLightState>()>> stateFactories_;
    std::map<std::string, std::vector<std::string>> transitionRules_;
    
public:
    TrafficLightStateManager() {
        std::cout << "🔄 创建交通灯状态管理器" << std::endl;
        initializeStateFactories();
        initializeTransitionRules();
    }
    
    void initializeStateFactories() {
        // 注册状态工厂
        stateFactories_["red"] = []() { return std::make_unique<RedLightState>(30); };
        stateFactories_["green"] = []() { return std::make_unique<GreenLightState>(45); };
        stateFactories_["yellow"] = []() { return std::make_unique<YellowLightState>(5); };
        stateFactories_["all_red"] = []() { return std::make_unique<AllRedState>(10); };
        stateFactories_["blinking_yellow"] = []() { return std::make_unique<BlinkingYellowState>(); };
        
        std::cout << "✅ 初始化 " << stateFactories_.size() << " 个状态工厂" << std::endl;
    }
    
    void initializeTransitionRules() {
        // 定义状态转换规则
        transitionRules_["red"] = {"green"};
        transitionRules_["green"] = {"yellow"};
        transitionRules_["yellow"] = {"red"};
        transitionRules_["all_red"] = {"red", "green"};
        transitionRules_["blinking_yellow"] = {"red", "green"};
        
        std::cout << "✅ 初始化状态转换规则" << std::endl;
    }
    
    std::unique_ptr<TrafficLightState> createState(const std::string& stateName) {
        auto it = stateFactories_.find(stateName);
        if (it != stateFactories_.end()) {
            std::cout << "🏭 创建状态: " << stateName << std::endl;
            return it->second();
        }
        std::cout << "❌ 未知状态: " << stateName << std::endl;
        return nullptr;
    }
    
    std::vector<std::string> getValidTransitions(const std::string& currentState) const {
        auto it = transitionRules_.find(currentState);
        if (it != transitionRules_.end()) {
            return it->second;
        }
        return {};
    }
    
    bool isValidTransition(const std::string& fromState, const std::string& toState) const {
        auto transitions = getValidTransitions(fromState);
        return std::find(transitions.begin(), transitions.end(), toState) != transitions.end();
    }
    
    void registerStateFactory(const std::string& stateName, 
                             std::function<std::unique_ptr<TrafficLightState>()> factory) {
        stateFactories_[stateName] = factory;
        std::cout << "🆕 注册状态工厂: " << stateName << std::endl;
    }
    
    void listAvailableStates() const {
        std::cout << "\n📋 可用状态 (" << stateFactories_.size() << " 个):" << std::endl;
        for (const auto& pair : stateFactories_) {
            std::cout << "   • " << pair.first << std::endl;
        }
    }
};

// 智能交通灯控制器
class SmartTrafficLightController {
private:
    TrafficLight& trafficLight_;
    TrafficLightStateManager& stateManager_;
    bool isRunning_;
    std::thread controlThread_;
    int cycleCount_;
    
public:
    SmartTrafficLightController(TrafficLight& light, TrafficLightStateManager& manager)
        : trafficLight_(light), stateManager_(manager), isRunning_(false), cycleCount_(0) {
        std::cout << "🎮 创建智能交通灯控制器: " << light.getLightId() << std::endl;
    }
    
    ~SmartTrafficLightController() {
        stop();
    }
    
    void start() {
        if (isRunning_) return;
        
        isRunning_ = true;
        controlThread_ = std::thread(&SmartTrafficLightController::controlLoop, this);
        std::cout << "▶️  启动交通灯控制器: " << trafficLight_.getLightId() << std::endl;
    }
    
    void stop() {
        if (!isRunning_) return;
        
        isRunning_ = false;
        if (controlThread_.joinable()) {
            controlThread_.join();
        }
        std::cout << "⏹️  停止交通灯控制器: " << trafficLight_.getLightId() << std::endl;
    }
    
    void setInitialState(const std::string& stateName) {
        auto state = stateManager_.createState(stateName);
        if (state) {
            trafficLight_.setState(std::move(state));
        }
    }
    
    void transitionTo(const std::string& targetState) {
        auto currentState = trafficLight_.getCurrentStateInfo();
        if (stateManager_.isValidTransition(getCurrentStateName(), targetState)) {
            auto newState = stateManager_.createState(targetState);
            if (newState) {
                trafficLight_.setState(std::move(newState));
            }
        } else {
            std::cout << "❌ 无效的状态转换: " << getCurrentStateName() << " → " << targetState << std::endl;
        }
    }
    
    void runStandardCycle() {
        std::cout << "\n🔄 执行标准循环..." << std::endl;
        
        transitionTo("green");
        trafficLight_.operate();
        
        transitionTo("yellow");
        trafficLight_.operate();
        
        transitionTo("red");
        trafficLight_.operate();
        
        cycleCount_++;
        std::cout << "✅ 完成标准循环 #" << cycleCount_ << std::endl;
    }
    
    void showControllerStatus() const {
        std::cout << "\n📊 控制器状态:" << std::endl;
        std::cout << "   运行状态: " << (isRunning_ ? "运行中" : "已停止") << std::endl;
        std::cout << "   当前状态: " << trafficLight_.getCurrentStateInfo() << std::endl;
        std::cout << "   循环次数: " << cycleCount_ << std::endl;
        std::cout << "   运行时间: " << trafficLight_.getUptime() << std::endl;
    }
    
private:
    void controlLoop() {
        std::cout << "🔄 控制器循环开始..." << std::endl;
        
        // 设置初始状态
        if (trafficLight_.getOperationCount() == 0) {
            setInitialState("red");
        }
        
        while (isRunning_) {
            runStandardCycle();
            
            // 模拟控制间隔
            std::this_thread::sleep_for(std::chrono::seconds(1));
            
            // 简化:运行5个循环后停止
            if (cycleCount_ >= 5) {
                break;
            }
        }
        
        std::cout << "🔄 控制器循环结束" << std::endl;
    }
    
    std::string getCurrentStateName() const {
        auto info = trafficLight_.getCurrentStateInfo();
        if (info.find("红灯") != std::string::npos) return "red";
        if (info.find("绿灯") != std::string::npos) return "green";
        if (info.find("黄灯") != std::string::npos) return "yellow";
        if (info.find("全红") != std::string::npos) return "all_red";
        if (info.find("闪烁黄灯") != std::string::npos) return "blinking_yellow";
        return "unknown";
    }
};

// 交通灯网络系统
class TrafficLightNetwork {
private:
    std::vector<std::unique_ptr<TrafficLight>> trafficLights_;
    std::vector<std::unique_ptr<SmartTrafficLightController>> controllers_;
    TrafficLightStateManager stateManager_;
    
public:
    TrafficLightNetwork() {
        std::cout << "🌐 创建交通灯网络系统" << std::endl;
        initializeNetwork();
    }
    
    void initializeNetwork() {
        // 创建多个交通灯
        std::vector<std::string> locations = {
            "主路口-南北", "主路口-东西", 
            "学校路口", "商业区路口", "住宅区路口"
        };
        
        for (const auto& location : locations) {
            auto light = std::make_unique<TrafficLight>(location);
            auto controller = std::make_unique<SmartTrafficLightController>(*light, stateManager_);
            
            // 设置不同的初始状态以模拟真实场景
            if (location.find("学校") != std::string::npos) {
                controller->setInitialState("blinking_yellow");
            } else if (location.find("主路口-南北") != std::string::npos) {
                controller->setInitialState("green");
            } else {
                controller->setInitialState("red");
            }
            
            trafficLights_.push_back(std::move(light));
            controllers_.push_back(std::move(controller));
        }
        
        std::cout << "✅ 初始化 " << trafficLights_.size() << " 个交通灯" << std::endl;
    }
    
    void startAll() {
        std::cout << "\n🚀 启动所有交通灯..." << std::endl;
        for (auto& controller : controllers_) {
            controller->start();
        }
    }
    
    void stopAll() {
        std::cout << "\n🛑 停止所有交通灯..." << std::endl;
        for (auto& controller : controllers_) {
            controller->stop();
        }
    }
    
    void showNetworkStatus() {
        std::cout << "\n📡 交通灯网络状态" << std::endl;
        std::cout << "==================" << std::endl;
        std::cout << "交通灯数量: " << trafficLights_.size() << std::endl;
        
        for (size_t i = 0; i < trafficLights_.size(); ++i) {
            std::cout << "\n" << (i + 1) << ". " << trafficLights_[i]->getLightId() << std::endl;
            std::cout << "   状态: " << trafficLights_[i]->getCurrentStateInfo() << std::endl;
            std::cout << "   操作次数: " << trafficLights_[i]->getOperationCount() << std::endl;
            std::cout << "   运行时间: " << trafficLights_[i]->getUptime() << std::endl;
        }
    }
    
    void simulateEmergency(const std::string& location) {
        std::cout << "\n🚨 模拟紧急情况: " << location << std::endl;
        
        for (size_t i = 0; i < trafficLights_.size(); ++i) {
            if (trafficLights_[i]->getLightId().find(location) != std::string::npos) {
                // 停止控制器
                controllers_[i]->stop();
                
                // 设置全红状态
                auto emergencyState = std::make_unique<AllRedState>(15, "紧急车辆通过");
                trafficLights_[i]->setState(std::move(emergencyState));
                trafficLights_[i]->operate();
                
                std::cout << "✅ " << location << " 进入紧急模式" << std::endl;
                break;
            }
        }
    }
    
    void runDemo() {
        std::cout << "\n🎮 运行交通灯网络演示..." << std::endl;
        std::cout << "=======================" << std::endl;
        
        showNetworkStatus();
        
        // 启动网络
        startAll();
        
        // 让系统运行一段时间
        std::this_thread::sleep_for(std::chrono::seconds(10));
        
        // 模拟紧急情况
        simulateEmergency("学校路口");
        
        // 停止网络
        stopAll();
        
        // 显示最终状态
        showNetworkStatus();
        
        // 显示历史
        std::cout << "\n--- 历史记录 ---" << std::endl;
        for (auto& light : trafficLights_) {
            light->showStateHistory(3);
        }
    }
};

高级状态特性

cpp 复制代码
// 带条件的状态:基于外部条件改变行为
class ConditionalTrafficLightState : public TrafficLightState {
protected:
    std::function<bool()> condition_;
    std::unique_ptr<TrafficLightState> trueState_;
    std::unique_ptr<TrafficLightState> falseState_;
    
public:
    ConditionalTrafficLightState(std::function<bool()> condition,
                                std::unique_ptr<TrafficLightState> trueState,
                                std::unique_ptr<TrafficLightState> falseState)
        : condition_(condition), trueState_(std::move(trueState)),
          falseState_(std::move(falseState)) {
        std::cout << "   ❓ 创建条件状态" << std::endl;
    }
    
    void handle(TrafficLight* context) override {
        bool conditionResult = condition_();
        std::cout << "   🔍 条件评估: " << (conditionResult ? "真" : "假") << std::endl;
        
        if (conditionResult) {
            std::cout << "   ➡️  执行真分支" << std::endl;
            trueState_->handle(context);
        } else {
            std::cout << "   ➡️  执行假分支" << std::endl;
            falseState_->handle(context);
        }
    }
    
    std::string getName() const override {
        return "条件状态[" + trueState_->getName() + "|" + falseState_->getName() + "]";
    }
    
    std::string getColor() const override { return "条件"; }
    int getDuration() const override { return 0; }
    std::string getNextState() const override { return "未知"; }
    
    bool canVehiclesGo() const override { return false; }
    bool canPedestriansCross() const override { return false; }
    bool isTransitional() const override { return true; }
};

// 状态历史跟踪器
class StateHistoryTracker {
private:
    struct StateRecord {
        std::string stateName;
        std::chrono::system_clock::time_point timestamp;
        int operationCount;
        
        StateRecord(const std::string& name, const std::chrono::system_clock::time_point& time, int count)
            : stateName(name), timestamp(time), operationCount(count) {}
        
        std::string toString() const {
            auto time = std::chrono::system_clock::to_time_t(timestamp);
            std::string timeStr = std::ctime(&time);
            timeStr.pop_back();
            
            std::stringstream ss;
            ss << "[" << timeStr << "] " << stateName << " (操作#" << operationCount << ")";
            return ss.str();
        }
    };
    
    std::vector<StateRecord> history_;
    int maxRecords_;
    
public:
    StateHistoryTracker(int maxRecords = 100) : maxRecords_(maxRecords) {
        std::cout << "📚 创建状态历史跟踪器,最大记录: " << maxRecords_ << std::endl;
    }
    
    void recordStateChange(const std::string& stateName, int operationCount) {
        StateRecord record(stateName, std::chrono::system_clock::now(), operationCount);
        history_.push_back(record);
        
        // 保持记录数量
        if (history_.size() > maxRecords_) {
            history_.erase(history_.begin());
        }
        
        std::cout << "📝 记录状态变更: " << stateName << " (#" << operationCount << ")" << std::endl;
    }
    
    void showHistory(int count = 10) const {
        int start = std::max(0, static_cast<int>(history_.size()) - count);
        std::cout << "\n📜 状态历史 (最近" << (history_.size() - start) << "个):" << std::endl;
        for (int i = start; i < history_.size(); ++i) {
            std::cout << "   " << (i + 1) << ". " << history_[i].toString() << std::endl;
        }
    }
    
    void analyzeStatePatterns() const {
        if (history_.empty()) {
            std::cout << "📊 无历史数据可供分析" << std::endl;
            return;
        }
        
        std::map<std::string, int> stateCounts;
        std::map<std::string, int> stateDurations; // 简化实现
        
        for (const auto& record : history_) {
            stateCounts[record.stateName]++;
        }
        
        std::cout << "\n📊 状态模式分析:" << std::endl;
        std::cout << "   总状态变更: " << history_.size() << std::endl;
        std::cout << "   不同状态数: " << stateCounts.size() << std::endl;
        
        for (const auto& pair : stateCounts) {
            double percentage = (pair.second * 100.0) / history_.size();
            std::cout << "   • " << pair.first << ": " << pair.second 
                      << " 次 (" << std::fixed << std::setprecision(1) << percentage << "%)" << std::endl;
        }
    }
    
    void clear() {
        history_.clear();
        std::cout << "🧹 清空状态历史" << std::endl;
    }
};

// 增强型交通灯:带历史跟踪
class EnhancedTrafficLight : public TrafficLight {
private:
    StateHistoryTracker historyTracker_;
    
public:
    EnhancedTrafficLight(const std::string& id) : TrafficLight(id) {
        std::cout << "🌟 创建增强型交通灯: " << id << std::endl;
    }
    
    void setState(std::unique_ptr<TrafficLightState> state) override {
        std::string newStateName = state->getName();
        TrafficLight::setState(std::move(state));
        historyTracker_.recordStateChange(newStateName, getOperationCount());
    }
    
    void showEnhancedHistory() const {
        showStateHistory();
        historyTracker_.showHistory();
    }
    
    void analyzeBehavior() const {
        std::cout << "\n🔍 交通灯行为分析: " << getLightId() << std::endl;
        std::cout << "   总操作次数: " << getOperationCount() << std::endl;
        std::cout << "   运行时间: " << getUptime() << std::endl;
        historyTracker_.analyzeStatePatterns();
    }
};

完整测试代码

cpp 复制代码
// 测试状态模式
void testStatePattern() {
    std::cout << "=== 状态模式测试开始 ===" << std::endl;
    
    // 创建交通灯
    std::cout << "\n--- 创建交通灯 ---" << std::endl;
    TrafficLight light("测试路口");
    
    // 测试各种状态
    std::cout << "\n--- 测试红灯状态 ---" << std::endl;
    light.setState(std::make_unique<RedLightState>(25));
    light.operate();
    
    std::cout << "\n--- 测试绿灯状态 ---" << std::endl;
    auto greenState = std::make_unique<GreenLightState>(40, 15);
    greenState->setVehicleCount(20);
    light.setState(std::move(greenState));
    light.operate();
    
    std::cout << "\n--- 测试黄灯状态 ---" << std::endl;
    auto yellowState = std::make_unique<YellowLightState>(5, true);
    yellowState->setWarningMode(false);
    light.setState(std::move(yellowState));
    light.operate();
    
    std::cout << "\n--- 测试全红状态 ---" << std::endl;
    light.setState(std::make_unique<AllRedState>(15, "测试紧急情况"));
    light.operate();
    
    std::cout << "\n--- 测试闪烁黄灯状态 ---" << std::endl;
    light.setState(std::make_unique<BlinkingYellowState>(8));
    light.operate();
    
    // 显示状态历史
    light.showStateHistory();
    
    std::cout << "\n=== 基础状态模式测试结束 ===" << std::endl;
}

// 测试状态管理器
void testStateManager() {
    std::cout << "\n=== 状态管理器测试开始 ===" << std::endl;
    
    TrafficLightStateManager manager;
    manager.listAvailableStates();
    
    // 测试状态创建
    std::cout << "\n--- 测试状态创建 ---" << std::endl;
    auto redState = manager.createState("red");
    if (redState) {
        std::cout << "   创建状态: " << redState->getDescription() << std::endl;
    }
    
    auto greenState = manager.createState("green");
    if (greenState) {
        std::cout << "   创建状态: " << greenState->getDescription() << std::endl;
    }
    
    // 测试转换规则
    std::cout << "\n--- 测试状态转换规则 ---" << std::endl;
    std::vector<std::pair<std::string, std::string>> testTransitions = {
        {"red", "green"},
        {"green", "yellow"}, 
        {"yellow", "red"},
        {"red", "yellow"} // 无效转换
    };
    
    for (const auto& transition : testTransitions) {
        bool isValid = manager.isValidTransition(transition.first, transition.second);
        std::cout << "   转换 " << transition.first << " → " << transition.second 
                  << ": " << (isValid ? "✅ 有效" : "❌ 无效") << std::endl;
    }
    
    std::cout << "\n=== 状态管理器测试结束 ===" << std::endl;
}

// 测试智能控制器
void testSmartController() {
    std::cout << "\n=== 智能控制器测试开始 ===" << std::endl;
    
    TrafficLight light("控制器测试路口");
    TrafficLightStateManager manager;
    SmartTrafficLightController controller(light, manager);
    
    // 显示初始状态
    controller.showControllerStatus();
    
    // 测试手动状态转换
    std::cout << "\n--- 测试手动状态转换 ---" << std::endl;
    controller.setInitialState("red");
    controller.transitionTo("green");
    controller.transitionTo("yellow");
    controller.transitionTo("red");
    
    // 测试标准循环
    std::cout << "\n--- 测试标准循环 ---" << std::endl;
    controller.runStandardCycle();
    
    // 显示最终状态
    controller.showControllerStatus();
    light.showStateHistory();
    
    std::cout << "\n=== 智能控制器测试结束 ===" << std::endl;
}

// 测试增强型交通灯
void testEnhancedTrafficLight() {
    std::cout << "\n=== 增强型交通灯测试开始 ===" << std::endl;
    
    EnhancedTrafficLight enhancedLight("增强测试路口");
    
    // 模拟状态变化序列
    std::vector<std::unique_ptr<TrafficLightState>> states;
    states.push_back(std::make_unique<RedLightState>(20));
    states.push_back(std::make_unique<GreenLightState>(35, 10));
    states.push_back(std::make_unique<YellowLightState>(4));
    states.push_back(std::make_unique<RedLightState>(25));
    states.push_back(std::make_unique<GreenLightState>(30, 8));
    states.push_back(std::make_unique<YellowLightState>(5));
    
    for (auto& state : states) {
        enhancedLight.setState(std::move(state));
        enhancedLight.operate();
    }
    
    // 显示增强功能
    enhancedLight.showEnhancedHistory();
    enhancedLight.analyzeBehavior();
    
    std::cout << "\n=== 增强型交通灯测试结束 ===" << std::endl;
}

// 实战应用:城市交通管理系统
class CityTrafficManagementSystem {
private:
    std::vector<std::unique_ptr<EnhancedTrafficLight>> trafficLights_;
    TrafficLightStateManager stateManager_;
    
public:
    CityTrafficManagementSystem() {
        std::cout << "🏙️  创建城市交通管理系统" << std::endl;
        initializeSystem();
    }
    
    void initializeSystem() {
        // 创建城市各路口交通灯
        std::vector<std::string> intersections = {
            "市中心-人民路", "市中心-解放路", "商业区-中山路", 
            "住宅区-幸福路", "学校区-学院路", "工业区-创业路"
        };
        
        for (const auto& intersection : intersections) {
            auto light = std::make_unique<EnhancedTrafficLight>(intersection);
            
            // 根据路口类型设置不同的初始状态
            if (intersection.find("学校") != std::string::npos) {
                light->setState(std::make_unique<BlinkingYellowState>());
            } else if (intersection.find("市中心") != std::string::npos) {
                light->setState(std::make_unique<GreenLightState>(40, 25));
            } else {
                light->setState(std::make_unique<RedLightState>(30));
            }
            
            trafficLights_.push_back(std::move(light));
        }
        
        std::cout << "✅ 系统初始化完成,管理 " << trafficLights_.size() << " 个路口" << std::endl;
    }
    
    void simulateCityTraffic() {
        std::cout << "\n🏙️  模拟城市交通运行..." << std::endl;
        
        // 模拟多个交通周期
        for (int cycle = 1; cycle <= 3; cycle++) {
            std::cout << "\n--- 交通周期 #" << cycle << " ---" << std::endl;
            
            for (auto& light : trafficLights_) {
                std::cout << "\n🚦 " << light->getLightId() << " 运行..." << std::endl;
                
                // 根据当前状态决定下一个状态
                auto currentInfo = light->getCurrentStateInfo();
                std::unique_ptr<TrafficLightState> nextState;
                
                if (currentInfo.find("红灯") != std::string::npos) {
                    nextState = std::make_unique<GreenLightState>(35, 15 + rand() % 10);
                } else if (currentInfo.find("绿灯") != std::string::npos) {
                    nextState = std::make_unique<YellowLightState>(4);
                } else if (currentInfo.find("黄灯") != std::string::npos) {
                    nextState = std::make_unique<RedLightState>(28);
                } else if (currentInfo.find("闪烁") != std::string::npos) {
                    // 夜间模式保持不变
                    nextState = std::make_unique<BlinkingYellowState>(6);
                    continue;
                }
                
                if (nextState) {
                    light->setState(std::move(nextState));
                    light->operate();
                }
            }
            
            // 周期间隔
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
        
        std::cout << "\n✅ 城市交通模拟完成" << std::endl;
    }
    
    void showSystemReport() {
        std::cout << "\n📊 城市交通管理系统报告" << std::endl;
        std::cout << "======================" << std::endl;
        
        for (auto& light : trafficLights_) {
            std::cout << "\n📍 " << light->getLightId() << std::endl;
            light->analyzeBehavior();
        }
        
        // 总体统计
        int totalOperations = 0;
        for (auto& light : trafficLights_) {
            totalOperations += light->getOperationCount();
        }
        
        std::cout << "\n📈 总体统计:" << std::endl;
        std::cout << "   管理路口数: " << trafficLights_.size() << std::endl;
        std::cout << "   总操作次数: " << totalOperations << std::endl;
        std::cout << "   平均操作数: " << (trafficLights_.empty() ? 0 : totalOperations / trafficLights_.size()) << std::endl;
    }
    
    void handleEmergency(const std::string& location, const std::string& reason) {
        std::cout << "\n🚨 处理紧急情况: " << location << " - " << reason << std::endl;
        
        for (auto& light : trafficLights_) {
            if (light->getLightId().find(location) != std::string::npos) {
                light->setState(std::make_unique<AllRedState>(20, reason));
                light->operate();
                std::cout << "✅ " << location << " 进入紧急模式" << std::endl;
                return;
            }
        }
        
        std::cout << "❌ 未找到指定路口: " << location << std::endl;
    }
    
    void runCityDemo() {
        std::cout << "\n🎮 运行城市交通管理演示..." << std::endl;
        std::cout << "========================" << std::endl;
        
        // 显示初始状态
        showSystemReport();
        
        // 模拟交通运行
        simulateCityTraffic();
        
        // 处理紧急情况
        handleEmergency("学校区", "校车通过");
        
        // 继续模拟
        simulateCityTraffic();
        
        // 显示最终报告
        showSystemReport();
    }
};

// 高级应用:自适应状态系统
class AdaptiveStateSystem {
private:
    std::map<std::string, std::function<std::unique_ptr<TrafficLightState>(int, int)>> adaptiveFactories_;
    
public:
    AdaptiveStateSystem() {
        std::cout << "🧠 创建自适应状态系统" << std::endl;
        initializeAdaptiveFactories();
    }
    
    void initializeAdaptiveFactories() {
        adaptiveFactories_["red"] = [](int trafficDensity, int timeOfDay) {
            int duration = 30;
            if (trafficDensity > 50) duration = 25; // 高流量时缩短红灯
            if (timeOfDay > 22 || timeOfDay < 6) duration = 40; // 夜间延长
            return std::make_unique<RedLightState>(duration);
        };
        
        adaptiveFactories_["green"] = [](int trafficDensity, int timeOfDay) {
            int duration = 45;
            int vehicleCount = 15;
            
            if (trafficDensity > 70) {
                duration = 60; // 高流量时延长绿灯
                vehicleCount = 30;
            } else if (trafficDensity < 30) {
                duration = 30; // 低流量时缩短绿灯
                vehicleCount = 8;
            }
            
            if (timeOfDay > 22 || timeOfDay < 6) {
                duration = 20; // 夜间缩短
                vehicleCount = 5;
            }
            
            auto state = std::make_unique<GreenLightState>(duration, vehicleCount);
            return state;
        };
        
        adaptiveFactories_["yellow"] = [](int trafficDensity, int timeOfDay) {
            int duration = 5;
            bool warning = (trafficDensity > 60); // 高流量时启用警告模式
            return std::make_unique<YellowLightState>(duration, warning);
        };
        
        std::cout << "✅ 初始化 " << adaptiveFactories_.size() << " 个自适应状态工厂" << std::endl;
    }
    
    std::unique_ptr<TrafficLightState> createAdaptiveState(const std::string& stateType, 
                                                          int trafficDensity, int timeOfDay) {
        auto it = adaptiveFactories_.find(stateType);
        if (it != adaptiveFactories_.end()) {
            std::cout << "🧠 创建自适应状态: " << stateType 
                      << " [流量:" << trafficDensity << "%, 时间:" << timeOfDay << "时]" << std::endl;
            return it->second(trafficDensity, timeOfDay);
        }
        return nullptr;
    }
    
    void runAdaptiveDemo() {
        std::cout << "\n🎯 运行自适应状态演示..." << std::endl;
        
        // 测试不同条件下的状态
        std::vector<std::tuple<std::string, int, int>> testConditions = {
            {"red", 80, 18},    // 高峰期红灯
            {"green", 20, 3},   // 深夜绿灯
            {"yellow", 65, 12}, // 中午黄灯
            {"green", 90, 8}    // 早高峰绿灯
        };
        
        for (const auto& condition : testConditions) {
            auto state = createAdaptiveState(std::get<0>(condition), 
                                           std::get<1>(condition), 
                                           std::get<2>(condition));
            if (state) {
                std::cout << "   生成状态: " << state->getDescription() << std::endl;
            }
        }
    }
};

int main() {
    std::cout << "🌈 设计模式武林大会 - 状态模式演示 🌈" << std::endl;
    std::cout << "====================================" << std::endl;
    
    // 测试基础状态模式
    testStatePattern();
    
    // 测试状态管理器
    testStateManager();
    
    // 测试智能控制器
    testSmartController();
    
    // 测试增强型交通灯
    testEnhancedTrafficLight();
    
    // 运行城市交通管理系统演示
    std::cout << "\n=== 城市交通管理系统演示 ===" << std::endl;
    CityTrafficManagementSystem citySystem;
    citySystem.runCityDemo();
    
    // 测试自适应状态系统
    std::cout << "\n=== 自适应状态系统演示 ===" << std::endl;
    AdaptiveStateSystem adaptiveSystem;
    adaptiveSystem.runAdaptiveDemo();
    
    // 测试交通灯网络
    std::cout << "\n=== 交通灯网络系统演示 ===" << std::endl;
    TrafficLightNetwork network;
    network.runDemo();
    
    std::cout << "\n🎉 状态模式演示全部完成!" << std::endl;
    
    return 0;
}

状态模式的武学心得

适用场景

  • 对象状态决定行为:当一个对象的行为取决于它的状态,并且它必须在运行时根据状态改变它的行为时
  • 状态转换明确:当操作中有庞大的多分支条件语句,且这些分支依赖于对象的状态时
  • 状态可枚举:当对象有多个状态,且状态数量相对固定时
  • 避免条件判断:当需要消除大量的条件判断语句,使代码更清晰时

优点

  • 局部化状态相关行为:将与特定状态相关的行为局部化,并且将不同状态的行为分割开来
  • 状态转换显式化:使状态转换显式化,通过设置不同的状态对象来转换状态
  • 状态对象可共享:如果状态对象没有实例变量,那么各个上下文可以共享一个状态对象
  • 符合开闭原则:易于添加新的状态和转换

缺点

  • 增加系统复杂度:如果状态数量很少且很少变化,使用该模式可能会显得过于复杂
  • 状态对象较多:每个状态都需要一个具体的状态类,可能导致类数量增加
  • 上下文依赖:状态对象需要了解上下文的信息,可能产生双向依赖

武林高手的点评

Strategy 赞叹道:"State 兄的状态管理确实精妙!能够如此优雅地处理对象状态的转换和行为变化,这在状态驱动的系统中确实无人能及。"

Command 也点头称赞:"State 兄专注于对象内部状态的管理,而我更关注请求的封装和执行。我们都涉及行为的动态变化,但关注点不同。"

State 谦虚回应:"诸位过奖了。每个模式都有其适用场景。在需要根据对象状态改变行为时,我的状态模式确实能发挥重要作用。但在需要封装操作请求时,Command 兄的方法更加合适。"

下章预告

在State展示完他那精妙的状态艺术后,Visitor 彬彬有礼地走出,向复杂的对象结构行礼。

"State 兄的状态管理确实精妙,但在不修改现有对象结构的前提下定义新操作方面,需要更加灵活的访问方式。" Visitor 优雅地说道,"下一章,我将展示如何通过访问者模式允许你在不修改现有对象结构的前提下,定义作用于这些元素的新操作!"

架构老人满意地点头:"善!对象结构的灵活访问确实是构建可扩展系统的关键。下一章,就请 Visitor 展示他的访问艺术!

相关推荐
g***78919 小时前
SpringBoot中使用TraceId进行日志追踪
spring boot·后端·状态模式
shuxiaohua2 天前
使用HttpURLConnection调用SSE采坑记录
状态模式
崎岖Qiu2 天前
状态模式与策略模式的快速区分与应用
笔记·设计模式·状态模式·策略模式·开闭原则
Jonathan Star3 天前
前端需要做单元测试吗?哪些适合做?
前端·单元测试·状态模式
一水鉴天4 天前
整体设计 全面梳理复盘 之40 M3 统摄三层 AI 的动态运营社区(Homepage)设计
架构·transformer·状态模式·公共逻辑
前端玖耀里7 天前
Vue + Axios + Node.js(Express)如何实现无感刷新Token?
状态模式
将编程培养成爱好8 天前
C++ 设计模式《外卖骑手状态系统》
c++·ui·设计模式·状态模式
向葭奔赴♡8 天前
Spring Boot参数校验全流程解析
状态模式
阿珊和她的猫9 天前
Webpack 打包体积优化:让应用更轻量、更高效
前端·webpack·状态模式
Jonathan Star10 天前
在 LangFlow 中,**节点(Node)是构成工作流的核心基本单元**
状态模式