今日已更新 35 条资讯 | 累计 37284 条内容
关于我们

标签:#statemachine

找到 1 篇相关文章

AI 资讯

The State Pattern Trap: Why GoF Is Not Always the Best Choice

Have you ever tried to use the classic Gang of Four (GoF) State Pattern in real code? You might have hit a wall. You might have thought, "Wait, this feels way too connected." You are not wrong about that. In school and many engineering interviews, the GoF State Pattern looks great. It promises to fix big, ugly switch statements. But real business rules are hard. When you use this pattern in real life, it can become a huge mess. Every state knows too much about the other states. Let us look at why this happens. We will learn the difference between the GoF pattern and a Finite State Machine (FSM). We will also learn when to use each one. The False Promise of the GoF State Pattern The main idea of the GoF State Pattern is to spread out the work. The main object gives its work to state objects. But there is a catch. The state classes themselves must trigger the change to the next state. Example: The Traffic Light Think about a simple traffic light. It goes Red to Green to Yellow to Red. It does this forever. class RedState implements TrafficLightState { change ( context : TrafficLight ): void { console . log ( " RED light, Stop " ); context . setState ( new GreenState ()); // Very connected! } } The Problem: RedState is forced to know about GreenState . This is fine for a simple traffic light. It is a closed loop. The rules will never change. But what happens when business rules change? Imagine the city council makes a new rule. From midnight to 5:00 AM, the light must flash yellow. Now, you must open your RedState and YellowState classes. You have to add new time checks. You have to add the new flashing state. The more states you add, the messier your code gets. The Better Choice: The Central FSM In the real world, things do not always happen in a straight line. An online order does not just go from Pending to Shipped to Delivered. It can jump from Pending to Cancelled. It can go from Shipped to Returned. If you use GoF here, your PendingState needs to know about many

2026-08-26 原文 →