Practice
from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardStrategy(PaymentStrategy):
def pay(self, amount):
print(f"Processing credit card payment of ${amount}")
class UPIStrategy(PaymentStrategy):
def pay(self, amount):
print(f"Processing UPI payment of ${amount}")
class PaymentStrategyFactory:
@staticmethod
def get_strategy(method):
if method == 'CreditCard':
return CreditCardStrategy()
elif method == 'UPI':
return UPIStrategy()
else:
raise ValueError('Invalid payment method')
class PaymentProcessor:
def __init__(self, strategy: PaymentStrategy):
self.strategy = strategy
def pay(self, amount):
self.strategy.pay(amount)
processor = PaymentProcessor(PaymentStrategyFactory.get_strategy('UPI'))
processor.pay(100)
Solution
Step 1: Trace strategy selection
The factory methodget_strategy('UPI')returns an instance ofUPIStrategy.Step 2: Trace payment method call
Thepaymethod ofUPIStrategyprints "Processing UPI payment of $100".Final Answer:
Option D -> Option DQuick Check:
Correct strategy instance leads to correct output [OK]
- Confusing strategy returned or output string
Solution
Step 1: Identify stack initialization issue
Stack is initialized with children in original order, not reversed, causing traversal order reversal.Step 2: Confirm impact on traversal order
Without reversing, popping from stack yields children in reverse order, breaking expected traversal.Final Answer:
Option A -> Option AQuick Check:
Reversing children on stack initialization fixes traversal order [OK]
- Forgetting to reverse children on stack push
- Misplacing hasNext() check
Solution
Step 1: Recall LSP precondition rule
Subclasses must not strengthen preconditions; they can only maintain or weaken them.Step 2: Analyze each statement
A subclass can strengthen preconditions of an inherited method to ensure better input validation. is incorrect because strengthening preconditions breaks substitutability. A subclass must not weaken postconditions of an inherited method. is correct; subclasses can weaken postconditions. Covariance in return types is allowed under LSP. is correct; covariance in return types is allowed. Contravariance in method parameter types is allowed under LSP. is correct; contravariance in parameter types is allowed.Final Answer:
Option A -> Option AQuick Check:
Strengthening preconditions violates LSP.
- Confusing precondition and postcondition rules
- Believing strengthening preconditions is safe
- Misunderstanding covariance and contravariance
Solution
Step 1: Analyze statement A
OCP does not forbid all modifications; it encourages minimizing changes to stable, tested code but allows modifications when necessary.Step 2: Validate other statements
Statements B, C, and D correctly describe OCP's goals and mechanisms.Step 3: Why A is incorrect
Absolute prohibition of modification is impractical; OCP is about minimizing and isolating changes.Final Answer:
Option A -> Option AQuick Check:
OCP is about minimizing, not forbidding, modifications.
- Interpreting OCP as no code changes ever allowed
- Ignoring the role of abstraction in OCP
- Underestimating OCP's impact on bug reduction
Solution
Step 1: Understand reuse implications
Reusing leaves means the same component can appear multiple times, risking infinite loops.Step 2: Identify solution to prevent infinite loops
Tracking visited components prevents revisiting the same node repeatedly during iteration.Final Answer:
Option C -> Option CQuick Check:
Visited set avoids infinite loops with shared components [OK]
- Assuming no changes needed
- Changing push order does not fix reuse loops
