Design Patterns

Design Patterns

Top Interview Questions

About Design Patterns

Design Patterns are reusable solutions to common problems that occur in software design. They are not finished code or ready-made libraries, but rather proven templates or blueprints that developers can adapt to solve recurring design challenges in a consistent and efficient way.

Think of design patterns as best practices developed over time by experienced software engineers—they help you write code that is flexible, reusable, maintainable, and easy to understand.


What are Design Patterns?

In software engineering, developers often encounter similar problems when designing systems. Instead of reinventing solutions each time, design patterns provide standardized approaches to solving these problems.

A design pattern typically includes:

  • A problem (what issue it solves)

  • A solution (how it solves it)

  • The context (when to use it)

  • The consequences (pros and cons)

They are especially important in object-oriented programming (OOP), where managing relationships between classes and objects is crucial.


History of Design Patterns

Design patterns became widely popular after the publication of the book Design Patterns: Elements of Reusable Object-Oriented Software by four authors known as the Gang of Four (GoF):

  • Erich Gamma

  • Richard Helm

  • Ralph Johnson

  • John Vlissides

This book introduced 23 classic design patterns that are still widely used today.


Why are Design Patterns Important?

Design patterns play a critical role in software development:

1. Reusability

They provide tried-and-tested solutions that can be reused across projects.

2. Maintainability

Code written using patterns is easier to understand, modify, and extend.

3. Scalability

Patterns help build systems that can grow without major redesign.

4. Communication

Developers can communicate ideas quickly using common pattern names like “Singleton” or “Factory.”

5. Best Practices

They encapsulate years of experience and proven techniques.


Categories of Design Patterns

Design patterns are broadly divided into three categories:


1. Creational Patterns

These patterns deal with object creation mechanisms, making the system more flexible and reusable.

Common Creational Patterns:

Singleton Pattern

Ensures that a class has only one instance and provides a global access point.

Use Case: Logging systems, configuration settings


Factory Method Pattern

Defines an interface for creating objects but lets subclasses decide which class to instantiate.

Use Case: Creating objects without specifying exact classes


Abstract Factory Pattern

Provides an interface for creating families of related objects.

Use Case: UI frameworks supporting multiple themes


Builder Pattern

Separates the construction of a complex object from its representation.

Use Case: Building complex objects step by step (e.g., constructing a house or a car)


Prototype Pattern

Creates new objects by copying an existing object.

Use Case: When object creation is expensive


2. Structural Patterns

These patterns deal with object composition and relationships between classes.

Common Structural Patterns:

Adapter Pattern

Allows incompatible interfaces to work together.

Use Case: Integrating new systems with legacy code


Bridge Pattern

Separates abstraction from implementation so they can vary independently.


Composite Pattern

Treats individual objects and groups of objects uniformly.

Use Case: File systems (files and folders)


Decorator Pattern

Adds new functionality to an object dynamically.

Use Case: Adding features without modifying existing code


Facade Pattern

Provides a simplified interface to a complex system.

Use Case: Simplifying APIs


Proxy Pattern

Provides a placeholder or surrogate for another object.

Use Case: Access control, lazy loading


3. Behavioral Patterns

These patterns focus on communication between objects.

Common Behavioral Patterns:

Observer Pattern

Defines a one-to-many relationship where changes in one object notify others.

Use Case: Event systems, notifications


Strategy Pattern

Defines a family of algorithms and makes them interchangeable.

Use Case: Payment methods, sorting algorithms


Command Pattern

Encapsulates a request as an object.

Use Case: Undo/redo functionality


State Pattern

Allows an object to change behavior when its state changes.


Chain of Responsibility Pattern

Passes a request along a chain of handlers.


Mediator Pattern

Reduces direct communication between objects by introducing a mediator.


Real-World Analogy

Design patterns can be compared to architectural blueprints.

For example:

  • A Singleton is like a government office—only one exists.

  • A Factory is like a manufacturing unit producing different products.

  • An Observer is like a subscription service where users get updates automatically.


Example: Factory Pattern (Simple Explanation)

Imagine you are building a notification system.

Instead of writing:

  • EmailNotification

  • SMSNotification

  • PushNotification

You create a factory that returns the correct object based on input.

This way:

  • You don’t need to change existing code when adding new types

  • You follow the Open/Closed Principle


Design Patterns and SOLID Principles

Design patterns often work hand-in-hand with SOLID principles, which are guidelines for writing clean and maintainable code.

For example:

  • Singleton supports controlled access

  • Strategy follows the Open/Closed Principle

  • Observer supports loose coupling


Advantages of Design Patterns

  • Proven solutions reduce risk

  • Improve code readability

  • Encourage best practices

  • Speed up development

  • Promote loose coupling


Disadvantages of Design Patterns

  • Can add unnecessary complexity if overused

  • Not always needed for small projects

  • Requires understanding to apply correctly


When to Use Design Patterns

Use design patterns when:

  • You encounter recurring design problems

  • You need scalable and maintainable solutions

  • You want to follow best practices

Avoid using them:

  • For simple problems

  • When they make code harder to understand


Design Patterns in Modern Development

Design patterns are used in:

  • Web development frameworks

  • Mobile applications

  • Enterprise systems

  • Game development

Many modern frameworks internally use design patterns:

  • MVC (Model-View-Controller)

  • Dependency Injection

  • Event-driven architectures


Best Practices

  • Understand the problem before choosing a pattern

  • Don’t force a pattern where it’s not needed

  • Keep code simple and readable

  • Combine patterns when necessary


Conclusion

Design patterns are essential tools for software developers. They provide reusable, scalable, and efficient solutions to common design problems. By understanding and applying these patterns, developers can build systems that are not only functional but also elegant and maintainable.

Mastering design patterns takes time and practice, but once learned, they significantly improve your ability to design robust and flexible software systems.

Fresher Interview Questions

 

🧠 PART 1: Basics of Design Patterns

1. What are Design Patterns?

Answer:
Design Patterns are reusable solutions to common software design problems.

They are:

  • Not code, but templates

  • Proven best practices

  • Language-independent

πŸ‘‰ Example: Singleton ensures only one object exists.


2. Who introduced Design Patterns?

Answer:
Design patterns were popularized by the “Gang of Four (GoF)”:

  • Erich Gamma

  • Richard Helm

  • Ralph Johnson

  • John Vlissides


3. Why use Design Patterns?

Answer:

  • Improve code reusability

  • Make code maintainable

  • Provide standard solutions

  • Improve communication among developers


4. What are the main categories?

Answer:

  1. Creational → Object creation

  2. Structural → Class/object composition

  3. Behavioral → Object interaction


5. Difference between Design Pattern and Algorithm?

Answer:

Design Pattern Algorithm
Structure of code Step-by-step solution
Reusable design Problem-solving logic
High-level Low-level

πŸ—οΈ PART 2: Creational Patterns

6. What is Singleton Pattern?

Answer:
Ensures only one instance of a class exists.

Use cases:

  • Logger

  • Database connection

Example:

class Singleton:
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

7. Advantages of Singleton?

Answer:

  • Controlled access

  • Saves memory

  • Global access point


8. Disadvantages of Singleton?

Answer:

  • Hard to test

  • Global state issues

  • Tight coupling


9. What is Factory Pattern?

Answer:
Creates objects without exposing creation logic.

Example:

ShapeFactory.getShape("Circle")

10. Factory vs Constructor?

Answer:

  • Constructor → Direct object creation

  • Factory → Encapsulates creation logic


11. What is Abstract Factory?

Answer:
Creates families of related objects.

πŸ‘‰ Example: UI components for Windows/Mac


12. Factory vs Abstract Factory?

Answer:

  • Factory → One product

  • Abstract Factory → Multiple related products


13. What is Builder Pattern?

Answer:
Used to construct complex objects step-by-step.

πŸ‘‰ Example: Building a house or meal


14. What is Prototype Pattern?

Answer:
Creates objects by cloning existing ones.

πŸ‘‰ Faster than creating from scratch


🧩 PART 3: Structural Patterns

15. What is Adapter Pattern?

Answer:
Converts one interface into another.

πŸ‘‰ Example: Charger adapter


16. What is Decorator Pattern?

Answer:
Adds new functionality without modifying existing code.

πŸ‘‰ Example: Adding toppings to pizza


17. Decorator vs Inheritance?

Answer:

  • Decorator → Runtime flexibility

  • Inheritance → Compile-time


18. What is Facade Pattern?

Answer:
Provides a simplified interface to complex systems.

πŸ‘‰ Example: One API to call multiple services


19. What is Proxy Pattern?

Answer:
Acts as a placeholder or controller for another object.

πŸ‘‰ Example: Lazy loading images


20. What is Composite Pattern?

Answer:
Treats individual and group objects uniformly.

πŸ‘‰ Example: File system (files + folders)


21. What is Bridge Pattern?

Answer:
Separates abstraction from implementation.

πŸ‘‰ Helps independent development


22. What is Flyweight Pattern?

Answer:
Reduces memory usage by sharing objects.

πŸ‘‰ Example: Text editor characters


πŸ”„ PART 4: Behavioral Patterns

23. What is Observer Pattern?

Answer:
One object notifies multiple observers.

πŸ‘‰ Example: YouTube subscribers


24. What is Strategy Pattern?

Answer:
Encapsulates interchangeable algorithms.

πŸ‘‰ Example: Payment methods


25. Strategy vs Conditional Statements?

Answer:

  • Strategy → Clean and extensible

  • If-else → Hard to maintain


26. What is Command Pattern?

Answer:
Encapsulates request as an object.

πŸ‘‰ Example: Remote control


27. What is State Pattern?

Answer:
Changes behavior when state changes.

πŸ‘‰ Example: Traffic light


28. What is Template Method?

Answer:
Defines skeleton of algorithm.

πŸ‘‰ Subclasses override steps


29. What is Iterator Pattern?

Answer:
Provides a way to access elements sequentially.


30. What is Mediator Pattern?

Answer:
Centralizes communication between objects.


31. What is Chain of Responsibility?

Answer:
Passes request along chain until handled.

πŸ‘‰ Example: Approval system


32. What is Memento Pattern?

Answer:
Saves object state for rollback.

πŸ‘‰ Example: Undo feature


33. What is Interpreter Pattern?

Answer:
Evaluates language grammar.


34. What is Visitor Pattern?

Answer:
Adds new operations without modifying classes.


🧠 PART 5: Practical & Scenario-Based

35. Which pattern for logging system?

Answer:
Singleton → Single logger instance


36. Which pattern for payment system?

Answer:
Strategy → Multiple payment methods


37. Which pattern for notification system?

Answer:
Observer → Notify multiple users


38. Which pattern for UI themes?

Answer:
Abstract Factory


39. Which pattern for undo feature?

Answer:
Memento


40. Which pattern to reduce object creation cost?

Answer:
Prototype


41. Which pattern to simplify complex APIs?

Answer:
Facade


42. Which pattern to add features dynamically?

Answer:
Decorator


🎯 How to Answer in Interview

When asked about a pattern:

πŸ‘‰ Follow this structure:

  1. Definition

  2. Real-world example

  3. Use case

  4. Pros/cons


πŸ’‘ Quick Cheat Sheet

Pattern Use Case
Singleton One instance
Factory Object creation
Builder Complex objects
Adapter Compatibility
Observer Notifications
Strategy Multiple algorithms

πŸš€ Pro Tips for Freshers

  • Don’t memorize blindly—understand use cases

  • Always give real-world analogy

  • Focus on 5–7 most common patterns deeply

  • Practice explaining in simple words

Experienced Interview Questions

 

πŸ”· SECTION 1: CREATIONAL PATTERNS


1. What is the Singleton Pattern? When should you use it?

Answer

The Singleton Pattern ensures a class has only one instance and provides a global access point.

Use cases:

  • Logging systems

  • Configuration managers

  • Connection pools

Implementation (Thread-safe in Java)

public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null)
                    instance = new Singleton();
            }
        }
        return instance;
    }
}

Trade-offs:

  • ❌ Hard to test (global state)

  • ❌ Breaks SRP

  • βœ… Controlled access


2. What are drawbacks of Singleton?

  • Hidden dependencies

  • Difficult unit testing

  • Concurrency issues (if poorly implemented)

  • Tight coupling

πŸ‘‰ Better alternative: Dependency Injection


3. What is Factory Method Pattern?

Answer

The Factory Method Pattern defines an interface for object creation but lets subclasses decide the instantiation.

Example:

interface Shape {
    void draw();
}

class Circle implements Shape {}
class Square implements Shape {}

abstract class ShapeFactory {
    abstract Shape createShape();
}

Use case:

  • When object creation logic is complex


4. Factory vs Abstract Factory?

Answer

Feature Factory Method Abstract Factory
Scope Single object Family of objects
Complexity Low High
Example Shape UI toolkit

πŸ‘‰ Abstract Factory Pattern creates related objects (e.g., buttons + checkboxes for Windows/Mac)


5. What is Builder Pattern?

Answer

The Builder Pattern constructs complex objects step-by-step.

Example:

User user = new User.Builder()
    .setName("John")
    .setAge(30)
    .build();

Use case:

  • Many optional parameters


6. Builder vs Constructor?

  • Constructor → messy with many params

  • Builder → readable, flexible


7. What is Prototype Pattern?

Answer

The Prototype Pattern creates objects by cloning existing ones.

Use case:

  • Expensive object creation

  • Copying configurations


8. Shallow vs Deep Copy?

  • Shallow → references copied

  • Deep → full object cloned


9. When NOT to use Prototype?

  • Complex object graphs

  • Circular dependencies


πŸ”· SECTION 2: STRUCTURAL PATTERNS


10. What is Adapter Pattern?

Answer

The Adapter Pattern converts one interface into another.

Example:

  • Integrating legacy systems


11. Adapter vs Facade?

Adapter Facade
Converts interface Simplifies interface
Focus on compatibility Focus on usability

πŸ‘‰ Facade Pattern


12. What is Decorator Pattern?

Answer

The Decorator Pattern adds behavior dynamically.

Example:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));

13. Decorator vs Inheritance?

  • Decorator → runtime flexibility

  • Inheritance → compile-time


14. What is Proxy Pattern?

Answer

The Proxy Pattern controls access to an object.

Types:

  • Virtual proxy

  • Security proxy

  • Caching proxy


15. Proxy vs Decorator?

  • Proxy → control access

  • Decorator → add behavior


16. What is Composite Pattern?

Answer

The Composite Pattern treats individual and group objects uniformly.

Example:

  • File system (file + folder)


17. What is Bridge Pattern?

Answer

The Bridge Pattern decouples abstraction from implementation.


18. When to use Bridge?

  • Multiple dimensions of variation


19. What is Flyweight Pattern?

Answer

The Flyweight Pattern reduces memory by sharing objects.

Example:

  • Text editors (characters reuse)


20. Trade-offs of Flyweight?

  • Complex logic

  • Hard debugging


πŸ”· SECTION 3: BEHAVIORAL PATTERNS


21. What is Observer Pattern?

Answer

The Observer Pattern defines one-to-many dependency.

Example:

  • Event systems

  • UI updates


22. Observer vs Pub-Sub?

  • Observer → tight coupling

  • Pub-Sub → loosely coupled (via broker)


23. What is Strategy Pattern?

Answer

The Strategy Pattern defines interchangeable algorithms.

Example:

interface PaymentStrategy {}
class CreditCard implements PaymentStrategy {}
class UPI implements PaymentStrategy {}

24. Strategy vs State?

  • Strategy → interchangeable algorithms

  • State → object behavior changes internally


25. What is State Pattern?

Answer

The State Pattern changes behavior based on state.


26. What is Command Pattern?

Answer

The Command Pattern encapsulates a request as an object.

Use case:

  • Undo/redo

  • Task queues


27. What is Chain of Responsibility?

Answer

The Chain of Responsibility Pattern passes request along a chain.


28. What is Template Method Pattern?

Answer

The Template Method Pattern defines skeleton of algorithm.


29. What is Iterator Pattern?

Answer

The Iterator Pattern provides sequential access.


30. What is Mediator Pattern?

Answer

The Mediator Pattern reduces direct dependencies.


31. What is Memento Pattern?

Answer

The Memento Pattern captures object state.


32. What is Interpreter Pattern?

Answer

The Interpreter Pattern evaluates expressions.


33. What is Visitor Pattern?

Answer

The Visitor Pattern separates operations from object structure.


πŸ”· SECTION 4: ADVANCED & SCENARIO QUESTIONS


34. Which pattern is used in Spring Framework?

  • Singleton (default beans)

  • Proxy (AOP)

  • Factory


35. Which pattern is used in logging frameworks?

  • Singleton

  • Factory


36. How do design patterns improve scalability?

  • Decoupling

  • Reusability

  • Flexibility


37. Anti-patterns you’ve seen?

  • God object

  • Overuse of Singleton

  • Tight coupling


38. When NOT to use design patterns?

  • Over-engineering

  • Simple problems


39. Difference between design patterns and principles?

  • Patterns → solutions

  • Principles → guidelines (SOLID)


40. Real-world scenario: Payment system design?

Use:

  • Strategy → payment methods

  • Factory → create payment objects

  • Observer → notifications


41. Microservices + Design Patterns?

  • Circuit Breaker

  • API Gateway

  • Saga pattern


42. How do you choose a design pattern?

Steps:

  1. Identify problem

  2. Look for variability

  3. Choose pattern that reduces coupling


πŸ”₯ Final Interview Tip (Very Important)

At 4+ years, interviewers expect:

  • Not just definitions ❌

  • But why, when, trade-offs, real examples βœ