DEV Community

DIVAKAR UPADHYAY
DIVAKAR UPADHYAY

Posted on Originally published at devladder.pages.dev

Builder (Design Patterns)

👉 Full lesson with practice questions on DevLadder (free, lesson 4 of 18 in the Design Patterns (GoF + Enterprise) in C# course)

Construct a complex object step by step, separating construction from representation. Fluent builders are everywhere in .NET.

public class EmailBuilder
{
    private readonly MailMessage _m = new();
    public EmailBuilder From(string a) { _m.From = new MailAddress(a); return this; }
    public EmailBuilder To(string a) { _m.To.Add(a); return this; }
    public EmailBuilder Subject(string s) { _m.Subject = s; return this; }
    public EmailBuilder Html(string body) { _m.Body = body; _m.IsBodyHtml = true; return this; }
    public MailMessage Build() => _m.To.Count == 0 ? throw new InvalidOperationException("No recipient") : _m;
}

var mail = new EmailBuilder().From("hr@corp.test").To("divakar@corp.test").Subject("Offer").Html("<b>Welcome</b>").Build();

// .NET examples: WebApplication.CreateBuilder(), StringBuilder, UriBuilder, SqlConnectionStringBuilder, EF Core ModelBuilder
Enter fullscreen mode Exit fullscreen mode

Interview questions on Design Patterns (GoF + Enterprise) in C

What are design patterns? Name the three GoF categories.

Reusable, named solutions to recurring design problems. GoF (1994) lists 23 in three categories: Creational (Singleton, Factory Method, Abstract Factory, Builder, Prototype), Structural (Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy), Behavioural (Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor).

How do you implement a thread-safe Singleton in C#?

Use Lazy<T>: private static readonly Lazy<Svc> _i = new(() => new Svc()); public static Svc Instance => _i.Value; with a private constructor and a sealed class. Lazy<T> is thread-safe by default (ExecutionAndPublication). Alternatives: a static readonly field (thread-safe because of the type initialiser), or double-checked locking with volatile. In ASP.NET Core, prefer services.AddSingleton<ISvc, Svc>(). It's testable and the container manages the lifetime.

What is the difference between Factory Method and Abstract Factory?

Factory Method creates one product, and subclasses (or a method) decide which concrete class to create. Abstract Factory creates a family of related products through an interface with several create methods (button + textbox for a theme; connection + command + parameter for a DB provider). Factory Method uses inheritance; Abstract Factory uses composition (you pass the factory object).


Read the full lesson with progress tracking and the rest of the course on DevLadder: free step-by-step tutorials and interview questions for developers.

Next in the course: Prototype →

Top comments (0)