When is it safe to share a single instance of a state class across multiple context objects, and when does that become a bug?
It is safe when the state class is stateless — it holds no fields specific to any one context, so calling its methods on behalf of different objects can never leak data between them. A Walking state object that just returns a fixed ETA and a fixed directions string is a good example: every DirectionService in an application could share the exact same Walking instance without any risk. It stops being safe the moment a state needs to track something specific to the particular context it is attached to, such as how long that context has been in that state. At that point, two different contexts sharing one state instance would silently read and overwrite each other's data through the same shared object, which is a genuinely hard bug to trace back to its cause.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response