Design Patterns & Best Practices Interview Questions OOPs (original) (raw)

Last Updated : 1 Sep, 2025

Design Patterns & Best Practices in OOP provide proven solutions to recurring software design problems and guidelines for writing clean, maintainable code. Patterns like Singleton, Factory, Observer and Strategy help structure code efficiently, while best practices such as SOLID principles, DRY (Don’t Repeat Yourself) and favoring composition over inheritance ensure scalability and readability. Together, they enable developers to build flexible, reusable and robust object-oriented systems.

1. Why is the Singleton pattern sometimes considered an anti-pattern despite being widely used?

The Singleton pattern ensures only one instance of a class exists globally. While useful in scenarios like logging, configuration, or caching, it’s often criticized because:

Note: Thus, while practical, it must be carefully applied with thread-safe and dependency injection-friendly implementations.

2. How do you decide between using the Strategy pattern and the State pattern, since both encapsulate behavior?

Both Strategy and State encapsulate behavior in separate classes, but they serve different purposes:

Note: Use Strategy when behaviors are independent and interchangeable; use State when behavior depends on sequential state transitions.

3. Why is “Composition over Inheritance” considered a best practice in OOP design? Give an example.

**Example:
Instead of class Car extends Engine, use:

Java `

class Car { Engine engine; }

`

This allows swapping PetrolEngine with ElectricEngine at runtime without changing the Car class.

Note: Thus, composition promotes loose coupling, testability and runtime flexibility.

4. Explain how the Observer pattern can lead to a “memory leak” problem.

In the Observer pattern, subjects maintain references to observers. If an observer is no longer needed but not explicitly unsubscribed, the subject still holds a reference, preventing garbage collection -> memory leak. For example, in GUI frameworks, failing to deregister event listeners can cause hidden memory leaks.

**Solutions:

Note: The solution is to use weak references, automatic unsubscription mechanisms or event buses that clean up automatically.

5. What is the difference between the Factory Method and Abstract Factory patterns? When would you choose one over the other?

**Factory Method

**Abstract Factory

**Rule of thumb:

6. How can misuse of the Adapter pattern harm system performance?

The Adapter pattern bridges incompatible interfaces, but excessive use can:

Best practice: Use adapters sparingly and only for true interoperability, not as a substitute for good design.

7. Explain how the Dependency Inversion Principle (DIP) relates to the Factory and Dependency Injection (DI) patterns.

The Dependency Inversion Principle (DIP) is one of the five SOLID principles of object-oriented design. It states that: High-level modules (business logic) should not depend on low-level modules (concrete implementations).

**How DIP relates to Factory Pattern:

**How DIP relates to Dependency Injection (DI):

Note: DIP is the principle, while Factory and DI are mechanisms that implement it to reduce coupling and improve testability.

8. How does the Proxy pattern differ from the Decorator pattern, even though both wrap objects?

At first glance, both Proxy and Decorator patterns wrap another object and implement the same interface. However, their intent and purpose are different:

Proxy Pattern:

**Virtual Proxy: Delays object creation until it is actually needed (lazy loading). Example: An image viewer only loads the image when displayed.
**Remote Proxy: Represents an object in another address space (e.g., RMI in Java).
**Protection Proxy: Restricts access by checking permissions before delegating.

Decorator Pattern:

Adding compression, buffering, or encryption to a data stream.
Wrapping GUI components to add borders, scrollbars, or styles dynamically.

Example Difference:

9. Why can misuse of inheritance in design patterns lead to a violation of the Liskov Substitution Principle (LSP)?

The Liskov Substitution Principle (LSP) states: If S is a subtype of T, then objects of type T should be replaceable with objects of type S without altering correctness.

**How misuse of inheritance breaks LSP:

**Classic Example:

**Implications in Design Patterns:

Note: This breaks polymorphism and introduces bugs. Best practice: Favor composition and interfaces to avoid LSP violations.

10. Many developers treat design patterns as “templates to copy.” Why is this a bad practice?

Design patterns were popularized by the _Gang of Four (GoF) book as **solutions to recurring design problems. However, treating them as rigid templates to copy-paste into projects is a common mistake:

**Over-engineering:

**Loss of Context:

**Decreased Maintainability: Patterns add layers of abstraction. If not justified, this abstraction makes debugging and onboarding new developers harder.

**Misinterpretation of Intent: Developers may use a pattern because “it looks clever” rather than because it actually solves the design problem at hand.

Note: Design patterns should be conceptual guides, not copy-paste solutions. True mastery lies in knowing when not to use them.

11. How can overuse of design patterns lead to “Pattern Obsession” and what are its consequences?

**Pattern Obsession occurs when developers force-fit design patterns into every problem, regardless of whether they are needed. This often happens when teams focus more on _demonstrating pattern knowledge than solving the actual problem in the simplest way. Consequences:

**Over-engineering

**Reduced Readability and Maintainability

**Performance Issues

**Violation of YAGNI (You Aren’t Gonna Need It): Patterns are introduced to solve problems that don’t exist yet, leading to wasted development effort.

**Example:

**Note: Best practice is pragmatism, use patterns when they clearly solve recurring issues, not as a badge of expertise.

12. Explain how the Builder pattern solves the Telescoping Constructor Problem.

The Telescoping Constructor Problem occurs when a class has multiple optional parameters, leading to constructors like new User("A", "B", null, 0, true, null). This makes code unreadable and error-prone.
The Builder pattern addresses this by:

**Separation of Construction from Representation

**Step-by-Step Construction: Allows building objects gradually in a readable way ->

Java `

User user = new UserBuilder() .setFirstName("Alice") .setAge(30) .setAddress("NYC") .build();

`

Benefits:

This improves readability, maintainability and safety, especially in large systems.

13. In what scenarios is the Prototype pattern preferable over the Factory pattern?

Toth Prototype and Factory are creational patterns, but they shine in different contexts.

**Prototype Pattern: Creates new objects by cloning existing prototypes instead of instantiating new ones.

**When Prototype is preferable over Factory:

**Example: A Car Factory needs to create multiple car models with different configurations.

14. How does the Flyweight pattern balance memory optimization with increased complexity?

The Flyweight pattern is a structural pattern that minimizes memory usage by sharing common parts of state between multiple objects.

**Key Concept:

**Example: In a text editor, instead of storing font/color info for every character, you store it once in a shared Flyweight object. Each character then only stores its position (extrinsic state).

**Benefits (Pros):

  1. **Massive Memory Savings: Especially in systems with millions of similar objects (e.g., text editors, game engines with many sprites, particle systems).
  2. **Scalability: Makes large-scale object-heavy systems feasible.

Thus, it’s a trade-off between space efficiency and runtime complexity.

15. Can the Template Method pattern violate the Open/Closed Principle (OCP)? Why or why not?

The Template Method defines the skeleton of an algorithm in a superclass and lets subclasses override specific steps without changing the overall structure. Potential Violation of OCP:

**Subclass Fragility:

**Evolving Base Template: When the template itself changes (e.g., adding a new mandatory step), all subclasses must adapt. This breaks the OCP, since subclasses should ideally extend without forcing modifications upstream.

How to Avoid Violation:

Example:

Note: To avoid this, it’s often paired with Strategy (favoring composition) or hooks that allow extension without base class modification.

16. Compare Lazy Initialization in Singleton vs Proxy patterns.

Lazy initialization is a technique where object creation is delayed until it is actually required. Both Singleton and Proxy patterns use it, but for different goals:

**Singleton with Lazy Initialization:

**Proxy with Lazy Initialization:

**Key Difference:

17. How does the Command pattern improve undo/redo functionality in applications?

The Command pattern encapsulates a request as an object, decoupling the client (invoker) from the receiver (executor). This structure is especially powerful for implementing undo/redo features:

Note: This makes applications like IDEs, text editors and graphics software highly modular and flexible.

18. Why is the Mediator pattern often preferred over Observer in complex systems?

Both Mediator and Observer decouple components, but they scale differently:

**Observer Pattern:

**Mediator Pattern:

**Why preferred: Mediator reduces chaos, improves maintainability, centralizes complex interactions, and makes the system easier to evolve. Observer is better suited for smaller, lightweight event scenarios, but Mediator dominates in large-scale enterprise systems.

19. How does misuse of the Decorator pattern lead to the “Yo-Yo Problem”?

The Decorator pattern dynamically adds responsibilities to objects without modifying their class. However, excessive use can cause the “Yo-Yo Problem”:

**Definition: The Yo-Yo Problem refers to difficulty in tracing program behavior because of too many indirections or layers of abstraction.

**In Decorator Misuse:

**Solution:

20. In what way does the SOLID principle guide the correct application of design patterns?

Thus, SOLID is not a pattern itself but the philosophy behind using patterns correctly.