Design patterns · interview question
Consider the following code snippet. What is the best design pattern to refactor it?
Multiple choiceMediumchapter-13-curatedpremiumdesign-patternsfactory-pattern
class PaymentProcessor { void processPayment(String type) { if (type.equals("credit")) { new CreditCardProcessor(); } else { new PayPalProcessor(); } } }Answer and explanation
Correct answer
C. Factory Pattern
Why
The Factory Pattern is ideal here as it abstracts the instantiation of complex objects, making the codebase cleaner and more maintainable. It helps centralize the object creation logic.
Test yourself on Design patterns
A free test with instant, explained results. No account needed.
More Design patterns questions
- Which principle is most closely aligned with the Factory Pattern?
- Which scenario is least suited for the Decorator pattern?
- Why is it important for a decorator to share the same interface as the object it decorates?
- In an e-commerce application, you want to delay loading product images until they are actually needed. Which design…
- You are designing a system with multiple types of notifications (email, SMS, push). How can the Factory Pattern help…
- Which situation is the clearest example of over-engineering with the Strategy Pattern?