Behavioral PatternsStrategy PatternHard⏱️ ~4 min

Strategy Pattern - Interview Questions and Variations

Common Interview Questions

Question 1: How do you decide which strategy to use?

Answer: Strategy selection logic should NOT be in the context class (violates SRP). Use a Factory Pattern or Strategy Registry. The factory takes selection criteria (vehicle type, user preference) and returns the appropriate strategy instance. Example: PricingStrategyFactory.getStrategy(vehicleType) uses a map of VehicleType to Strategy classes. This keeps selection logic centralized and testable. If selection is simple, dependency injection at construction time is acceptable (client passes the strategy to context constructor).

Question 2: Can strategies maintain state?

Answer: Strategies CAN have state, but it is generally avoided for thread safety and reusability. If state is needed, two approaches work. First, pass all required data as method parameters (preferred, makes strategies stateless and reusable). Second, if strategies need configuration state (like tax rates or API keys), inject via constructor and keep that state immutable. Never store request-specific data (like current user or transaction ID) as instance variables if strategies are shared across requests.

Question 3: What if strategies need access to context data?

Answer: Three options exist. First, pass required data as method parameters (cleanest, explicit dependencies). Second, pass the entire context as a parameter, but this creates tight coupling (strategy knows about context structure). Third, use a callback interface where context implements methods that strategy can call (observer-like pattern). The first option is preferred unless the strategy needs to modify context state, in which case option two or three becomes necessary.

Interview Tip: If asked to design a payment system, start with Strategy for payment methods. Then they might ask about combining discounts (10% off + free shipping). That is when you introduce Decorator Pattern wrapping the base strategy, or a Chain of Responsibility for applying multiple discounts sequentially.

Machine Coding Considerations

First, start with the interface: Define Strategy interface with method signature first. This clarifies what data flows between context and strategies. In a 90-minute machine coding round, nail this interface before implementing concrete strategies, otherwise you will refactor repeatedly.

Second, implement one complete flow: Pick the simplest strategy (like flat-rate pricing), implement it fully with context, and test end-to-end. Then add additional strategies. Do not try to implement all strategies simultaneously.

Third, demonstrate extensibility: After basic implementation, add one more strategy without modifying existing code. Say out loud, "Notice I am not changing ParkingTicket or other pricing classes, demonstrating OCP." Interviewers look for this awareness.

Fourth, handle edge cases in strategies: What if duration is zero? Negative? What if a payment gateway times out? Put error handling IN the concrete strategy classes, not in the context. Context should be agnostic to strategy-specific failures, but might define a common exception hierarchy that all strategies throw.

Common Variations Asked

Variation 1: Dynamic strategy chaining

Question: "What if we need to apply multiple strategies in sequence, like calculate base price, then apply discount, then add tax?"

Answer: This is a Decorator Pattern use case, not pure Strategy. However, you can use a CompositeStrategy that holds a list of strategies and executes them in order, passing output of one as input to the next. Alternatively, Chain of Responsibility if each step can decide whether to pass to the next handler.

Variation 2: Strategy with fallback

Question: "Primary payment gateway fails. How do you fallback to secondary gateway?"

Answer: Implement a FallbackPaymentStrategy that wraps a list of strategies. It tries the first strategy, catches exceptions, and attempts the next on failure. This is a form of Proxy or Decorator Pattern combined with Strategy. The context remains unchanged, delegating to FallbackPaymentStrategy which handles retry logic internally.

Variation 3: Strategy selection based on multiple criteria

Question: "Pricing depends on vehicle type AND time of day AND customer loyalty tier. How do you handle this?"

Answer: Two approaches. First, create composite strategies like LoyaltyCarWeekendPricing, but this leads to class explosion. Second (better), use a Strategy Builder or Factory that composes behavior. For example, BasePricingStrategy calculates base rate, wrapped by LoyaltyDiscountDecorator, wrapped by PeakHourSurchargeDecorator. The Factory assembles this chain based on criteria. This demonstrates understanding of composing patterns.

Interview Tip: If the interviewer says "Now add feature X," and it requires modifying your strategy interface, that is acceptable. Acknowledge that interface changes are a design trade-off. Explain you would use the Adapter Pattern to wrap old strategies if backward compatibility is required, but if all strategies are under your control, updating the interface is cleaner.

Gotchas to Avoid

First, do NOT put strategy selection logic (if-else by type) inside context. That defeats the purpose. Use a factory or inject via constructor.

Second, do NOT make strategies aware of each other. If StrategyA needs to call StrategyB, you likely need a different pattern (Chain of Responsibility or mediator).

Third, do NOT use Strategy if only data differs, not behavior. Passing different parameters is simpler than creating classes.

Fourth, do NOT forget null checks. If context allows strategy to be null, handle gracefully (throw exception or use a default NullObject strategy).

💡 Key Takeaways
Use Factory or Strategy Registry for strategy selection, not conditionals in context
Prefer stateless strategies with data passed as parameters for thread safety
Strategies can access context data via parameters, not by storing context references
Demonstrate OCP by adding new strategies without modifying existing code
Handle chaining with Decorator or Composite patterns, not by coupling strategies
Strategy fallback implemented via wrapper strategy with retry logic
📌 Examples
1Factory pattern returning appropriate strategy based on vehicle type
2CompositeStrategy chaining multiple pricing rules (base + discount + tax)
3FallbackPaymentStrategy trying primary then secondary gateways
4Strategy Builder composing decorators for multi-criteria selection
← Back to Strategy Pattern Overview
Strategy Pattern - Interview Questions and Variations | Strategy Pattern - System Overflow