Feature | State Pattern | Strategy Pattern |
---|---|---|
Purpose | Manages an object's state transitions | Chooses an algorithm/behavior at runtime |
Problem it Solves | Vary behavior based on current state | Replace complex conditional logic with interchangeable algorithms |
Key Intent | Object changes behavior when its internal state changes | Encapsulate different algorithms behind a single interface |
Behavior Triggered By | Internal state of the object itself | External decision (e.g., user input, configuration) |
Context Awareness | Context object usually triggers state change itself | Client code chooses which strategy to use |
Participants | Context, State interface, Concrete States | Context, Strategy interface, Concrete Strategies |
Common Usage | Workflow engines, UI controls with multiple modes | Sorting algorithms, Payment gateways, Compression algorithms |
Dynamic Switching? | Yes, context switches between states itself | Yes, client switches the strategy explicitly |
Example Analogy | Phone: Ringing → Silent → Airplane Mode (state changes) | Payment Processor: CreditCard, PayPal, Apple Pay strategies |
Difference between State Pattern vs Strategy pattern
No comments:
Post a Comment