Design Pattern Q&A

 

100 C# Design Pattern Interview Questions & Answers

This post is designed to evaluate a developer's understanding of Design Patterns and their practical implementation using C#.

Part 1: Foundations & General Concepts (1-10)

1. What are Design Patterns? Reusable solutions to common problems in software design. They are templates for how to solve a problem that can be used in many different situations.

2. Name the three main categories of patterns defined by the Gang of Four (GoF).

  • Creational: Object creation mechanisms.

  • Structural: How classes and objects are composed to form larger structures.

  • Behavioral: Communication between objects.

3. What is the relationship between SOLID principles and Design Patterns? SOLID principles are the laws of good OOP; Design Patterns are the proven solutions that follow those laws.

4. What is an Anti-Pattern? A common response to a recurring problem that is usually ineffective and risks being highly counterproductive (e.g., God Object, Golden Hammer).

5. What is the difference between a Design Pattern and a Framework? A pattern is a concept/template you implement. A framework is actual code/libraries that call your code.

6. Why is "Program to an interface, not an implementation" critical for patterns? It allows for loose coupling, enabling objects to be swapped at runtime without changing the client code (polymorphism).

7. How do patterns improve code maintainability? They provide a common vocabulary for developers and enforce a structure that is easier to debug and extend.

8. Can a pattern be language-specific? While concepts are universal, implementation varies. For example, C# uses Events/Delegates to implement the Observer pattern natively.

9. What is "Favor Composition over Inheritance"? It means building complex functionality by combining objects (Has-A) rather than extending classes (Is-A), making the system more flexible.

10. What is the "Design Pattern Density" problem? Overusing patterns where they aren't needed, leading to "over-engineering" and unnecessary complexity.

Part 2: Creational Patterns (11-30)

11. Explain the Singleton Pattern and provide a thread-safe C# implementation. Ensures a class has only one instance and provides a global point of access.

public sealed class Singleton {
    private static readonly Lazy<Singleton> _instance = 
        new Lazy<Singleton>(() => new Singleton());
    public static Singleton Instance => _instance.Value;
    private Singleton() { } // Private constructor
}

12. When should you avoid Singleton? When you need to unit test (it introduces global state) or when you might need multiple instances in the future.

13. What is the Factory Method Pattern? Defines an interface for creating an object, but lets subclasses decide which class to instantiate.

public abstract class Creator {
    public abstract IProduct FactoryMethod();
}

14. Abstract Factory vs. Factory Method?

  • Factory Method: Creates one product.

  • Abstract Factory: Creates families of related products.

15. Explain the Builder Pattern. Separates the construction of a complex object from its representation, allowing the same construction process to create different representations. Useful for objects with many optional parameters.

16. Provide a C# example of a Fluent Builder.

var car = new CarBuilder()
    .SetEngine("V8")
    .SetWheels(4)
    .Build();

17. What is the Prototype Pattern? Creates new objects by copying an existing object (cloning). In C#, this often involves ICloneable or a custom Clone() method.

18. Deep Copy vs. Shallow Copy in Prototype?

  • Shallow: Copies values and references.

  • Deep: Recursively copies the objects the references point to.

19. How does the "Simple Factory" differ from the "Factory Method"? Simple Factory is usually a single class with a static method that returns different types based on input; Factory Method uses inheritance.

20. What problem does the "Object Pool" pattern solve? It reuses objects that are expensive to create (e.g., database connections) instead of creating/destroying them repeatedly.

(Questions 21-30 cover variations of Creational patterns, Lazy Initialization, and Static Factories...)

Part 3: Structural Patterns (31-55)

31. What is the Adapter Pattern? Allows incompatible interfaces to work together by wrapping an "Adaptee" with an "Adapter" that implements the expected interface.

32. Class Adapter vs. Object Adapter?

  • Class: Uses inheritance (multiple inheritance, which C# doesn't support for classes).

  • Object: Uses composition (Adapter holds an instance of Adaptee).

33. What is the Bridge Pattern? Decouples an abstraction from its implementation so that the two can vary independently (e.g., UI abstractions vs. different OS rendering).

34. Explain the Composite Pattern with an example. Treats individual objects and groups of objects uniformly (useful for tree structures like File Systems).

public interface IComponent { void Display(); }
public class Folder : IComponent {
    private List<IComponent> children = new();
    public void Display() { /* Show folder and children */ }
}

35. What is the Decorator Pattern? Dynamically adds behavior to an object without affecting others. It’s an alternative to inheritance.

public class CoffeeWithMilk : CoffeeDecorator {
    public CoffeeWithMilk(ICoffee coffee) : base(coffee) { }
    public override double GetCost() => base.GetCost() + 0.5;
}

36. Facade Pattern: When is it used? To provide a simplified, high-level interface to a complex set of classes or a library.

37. Flyweight Pattern: What is the goal? To reduce memory usage by sharing as much data as possible with similar objects (Intrinsic vs. Extrinsic state).

38. Proxy Pattern vs. Decorator Pattern?

  • Proxy: Controls access (Lazy loading, Security).

  • Decorator: Adds functionality.

39. Explain "Virtual Proxy" in C#. An object that stands in for a heavy object and only loads the real object when a method is actually called.

40. What is the "Protection Proxy"? Checks if a client has access rights before allowing them to call a sensitive operation.

(Questions 41-55 cover variations like Private Class Data, Twin, and Sidecar patterns...)

Part 4: Behavioral Patterns (56-85)

56. What is the Chain of Responsibility Pattern? Passes a request along a chain of handlers. Each handler decides to either process it or pass it to the next.

public abstract class Handler {
    protected Handler Successor;
    public void SetSuccessor(Handler successor) => Successor = successor;
    public abstract void HandleRequest(int amount);
}

57. How is the Command Pattern implemented for Undo/Redo? By storing a stack of command objects that each have an Execute() and an UnExecute() method.

58. What is the Iterator Pattern? Provides a way to access elements of a collection sequentially without exposing its underlying structure. In C#, this is baked-in via IEnumerable and IEnumerator.

59. Explain the Mediator Pattern. Reduces direct dependencies between objects by making them communicate through a mediator object (e.g., MediatR library in ASP.NET Core).

60. What is the Memento Pattern? Captures and externalizes an object's internal state so it can be restored later without violating encapsulation.

61. How does the Observer Pattern work in C#? One "Subject" notifies many "Observers" of state changes. In C#, we usually use event and delegate.

public event EventHandler OnDataChanged;

62. State Pattern vs. Strategy Pattern?

  • Strategy: Usually selected by the client to perform a specific task differently.

  • State: The object changes its own behavior automatically when its internal state changes.

63. What is the Template Method Pattern? Defines the steps of an algorithm in a base class but allows subclasses to override specific steps.

public abstract class DataProcessor {
    public void Process() { Read(); Transform(); Save(); } // Skeleton
    protected abstract void Transform(); // To be overridden
}

64. Explain the Strategy Pattern with an example.

public interface IShippingStrategy { double Calculate(Order order); }
public class FedexStrategy : IShippingStrategy { ... }

65. What is the Visitor Pattern? Allows adding new operations to existing object structures without modifying them. It uses "Double Dispatch."

(Questions 66-85 cover Interpreter, Null Object, Servant, and Specification patterns...)

Part 5: Practical & Architectural Patterns (86-100)

86. What is Dependency Injection (DI)? A pattern where an object receives its dependencies from an external source rather than creating them itself.

87. Service Locator vs. Dependency Injection?

  • Service Locator: The object asks for its dependency (container.Resolve<T>()).

  • DI: The dependency is "pushed" in (via Constructor). Service Locator is often considered an anti-pattern.

88. What is the Repository Pattern? Abstracts data access logic so that the rest of the application is unaware of whether data comes from SQL, a Web API, or a cache.

89. Unit of Work Pattern? Ensures that multiple repository operations share a single database transaction.

90. What is CQRS (Command Query Responsibility Segregation)? A pattern that separates read operations (Queries) from write operations (Commands) into different models.

91. Explain the "Options Pattern" in .NET. Uses classes to represent groups of related settings (Encapsulation of Configuration).

92. What is the "Circuit Breaker" pattern? Prevents an application from repeatedly trying to execute an operation that's likely to fail (used in microservices).

93. What is "Middleware" in ASP.NET Core? It is an implementation of the Chain of Responsibility pattern applied to HTTP requests.

94. How does the "Backends for Frontends" (BFF) pattern work? Creating separate backend services for different types of clients (Mobile vs. Web).

95. What is the "Saga Pattern"? Manages distributed transactions across microservices using a sequence of local transactions.

96. Difference between "Internal" and "External" Iterator?

  • External: The client controls the iteration (standard foreach).

  • Internal: The collection accepts a lambda and applies it to elements (e.g., .ForEach() in List).

97. What is the "Sidecar" pattern? Attaching a helper process/container to a primary application to provide extra features like logging or monitoring.

98. Explain "Inversion of Control" (IoC). A design principle where the control flow of a program is inverted: instead of the programmer calling library functions, the framework calls the programmer's code.

99. What pattern does the C# yield return implement? It implements the Iterator pattern by generating a state machine class behind the scenes.

100. How do you decide which pattern to use? Do not start with a pattern. Start with the problem. If the code becomes rigid or complex, identify the type of complexity (creation, structure, or behavior) and look for a pattern that specifically addresses that friction point.

No comments: