Practice
State interface defines methods like selectProduct(), insertMoney(), and dispense(). Concrete classes like IdleState, HasMoneyState, and SoldState implement this interface. Which design pattern is applied here and why is it the correct choice?Solution
Step 1: Identify the role of State interface and concrete states
TheStateinterface defines behavior that varies depending on the vending machine's current state. Concrete classes implement these behaviors and handle transitions.Step 2: Match pattern intent to scenario
The State pattern encapsulates state-specific behavior and transitions, allowing the vending machine to change behavior dynamically without complex conditionals.Final Answer:
Option D -> Option DQuick Check:
State pattern encapsulates state behavior and transitions [check]
Elevator class implement an interface or extend an abstract class to represent different elevator types (e.g., passenger, freight)? Consider that elevators share common state and behavior but also have type-specific logic.Solution
Step 1: Analyze shared state and behavior
Elevators share common fields like currentFloor, direction, and doorStatus, plus some implemented methods.Step 2: Abstract class fits shared state and partial behavior
Abstract class allows code reuse and enforces common state, while subclasses override type-specific logic.Final Answer:
Option A -> Option AQuick Check:
Abstract class supports shared state and behavior [check]
Vehicle abstraction for a parking system, should Vehicle be an abstract class or an interface if it needs to hold state like licensePlate? Why?Solution
Step 1: Identify state holding needs
licensePlateis shared state, which interfaces cannot hold as fields.Step 2: Evaluate options
Abstract classes can hold state and provide default behavior; interfaces cannot hold instance fields, only constants.Final Answer:
Option D -> Option DQuick Check:
Abstract class holds shared state like licensePlate [check]
WeekendFeeStrategy pricing rule in the Workflow Engine's fee calculation, which minimal change respects SOLID principles?Solution
Step 1: Identify SOLID principle involved
Open-Closed Principle (OCP) requires classes to be open for extension but closed for modification.Step 2: Apply OCP to fee strategy
Adding a new WeekendFeeStrategy class extends behavior without modifying existing FeeCalculator, respecting OCP and Dependency Inversion Principle.Final Answer:
Option B -> Option BQuick Check:
New strategy class + no FeeCalculator change -> OCP respected [check]
Solution
Step 1: Identify extensibility without modifying existing classes
Adding new enum values and subclass ElectricCar extends Vehicle allows new types without changing existing code.Step 2: Update SpotCompatibility.COMPATIBILITY_MAP to include new compatibility rules for charging spots.
Final Answer:
Option D -> Option DQuick Check:
New enums and subclass added, existing classes unchanged -> extensible design [check]
