15.1 Singleton
Guarantees a class has exactly one instance and a single global access point.
// Thread-safe Singleton using Lazy<T> — the modern, recommended approach in C#
public sealed class ConnectionPool
{
private static readonly Lazy<ConnectionPool> _instance =
new Lazy<ConnectionPool>(() => new ConnectionPool());
public static ConnectionPool Instance => _instance.Value;
private ConnectionPool() { /* initialize pool */ }
}
// A concrete, interview-friendly example: a token rate limiter that must be
// unique across the whole application to avoid blowing past an API's rate limit
public class OpenAIRateLimiter
{
private static readonly Lazy<OpenAIRateLimiter> _instance =
new Lazy<OpenAIRateLimiter>(() => new OpenAIRateLimiter());
public static OpenAIRateLimiter Instance => _instance.Value;
private OpenAIRateLimiter() { }
public bool CanMakeRequest() => /* token bucket check */ true;
}
# Thread-safe Singleton in Python (double-checked locking)
import threading
class ConnectionPool:
_instance = None
_lock = threading.Lock()
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None: # double-checked locking
cls._instance = super().__new__(cls)
cls._instance._init_pool()
return cls._instance
def _init_pool(self):
self.connections = [] # set up pool state once
DI Lifetime Discussion — the modern take on Singleton: in .NET Core and most Python DI frameworks, a hand-rolled static Singleton is essentially global mutable state, which makes unit testing hard (you can’t substitute a mock, tests leak state into each other via the shared static instance). The idiomatic modern equivalent is registering the type with singleton lifetime in the DI container:
services.AddSingleton<IConnectionPool, ConnectionPool>();
This gives the same “one instance for the app’s lifetime” guarantee and performance characteristics, but keeps the class loosely coupled (depends on an abstraction) and 100% mockable in tests — the container, not the class itself, enforces uniqueness. DI containers also expose Scoped (one instance per request/scope — the right choice for anything holding per-request state like a DbContext) and Transient (a new instance every time it’s resolved — for cheap, stateless services). A common interview trap: injecting a Scoped or Transient dependency into a Singleton service causes a captured-dependency bug (the singleton holds onto the first scope’s instance forever); .NET’s DI container throws a validation error for this by default in newer versions.
When to use: connection pools, configuration managers, distributed rate limiters, caches. Anti-pattern warning: don’t reach for a classic static Singleton by default — prefer DI-registered singleton lifetime for testability, and only use the classic pattern in code with no DI container available.
15.2 Factory Method & Abstract Factory
// Factory Method — creates ONE product, subclasses/switch decide the concrete type
public interface INotificationFactory
{
INotification Create(NotificationType type);
}
public class NotificationFactory : INotificationFactory
{
public INotification Create(NotificationType type) => type switch
{
NotificationType.Email => new EmailNotification(),
NotificationType.Sms => new SmsNotification(),
NotificationType.Push => new PushNotification(),
_ => throw new ArgumentException($"Unknown type: {type}")
};
}
// Abstract Factory — creates a FAMILY of related products that must stay consistent
public interface ICloudServiceFactory
{
IStorageService CreateStorage();
IComputeService CreateCompute();
IMessageQueue CreateQueue();
}
public class AzureServiceFactory : ICloudServiceFactory
{
public IStorageService CreateStorage() => new AzureBlobStorage();
public IComputeService CreateCompute() => new AzureContainerApps();
public IMessageQueue CreateQueue() => new AzureServiceBus();
}
public class AwsServiceFactory : ICloudServiceFactory
{
public IStorageService CreateStorage() => new S3Storage();
public IComputeService CreateCompute() => new EcsFargate();
public IMessageQueue CreateQueue() => new SqsQueue();
}
# Factory Method and Abstract Factory in Python
from abc import ABC, abstractmethod
from enum import Enum, auto
class NotificationType(Enum):
EMAIL = auto()
SMS = auto()
PUSH = auto()
class INotification(ABC):
@abstractmethod
def send(self, message: str) -> None: ...
class EmailNotification(INotification):
def send(self, message: str) -> None:
print(f"Emailing: {message}")
class SmsNotification(INotification):
def send(self, message: str) -> None:
print(f"Texting: {message}")
def notification_factory(kind: NotificationType) -> INotification:
"""Factory Method — decides WHICH concrete type to instantiate."""
mapping = {
NotificationType.EMAIL: EmailNotification,
NotificationType.SMS: SmsNotification,
}
cls = mapping.get(kind)
if cls is None:
raise ValueError(f"Unknown type: {kind}")
return cls()
# Abstract Factory — a FAMILY of related objects created together
class ICloudServiceFactory(ABC):
@abstractmethod
def create_storage(self): ...
@abstractmethod
def create_compute(self): ...
@abstractmethod
def create_queue(self): ...
class AzureServiceFactory(ICloudServiceFactory):
def create_storage(self): return AzureBlobStorage()
def create_compute(self): return AzureContainerApps()
def create_queue(self): return AzureServiceBus()
class AwsServiceFactory(ICloudServiceFactory):
def create_storage(self): return S3Storage()
def create_compute(self): return EcsFargate()
def create_queue(self): return SqsQueue()
When to use: Factory Method when object creation logic is conditional and you want callers decoupled from the concrete type; Abstract Factory when you need to guarantee a consistent family of related objects (e.g., never mixing an Azure storage client with an AWS queue client).
15.3 Builder
public class QueryBuilder
{
private string _table;
private readonly List<string> _conditions = new();
private string _orderBy;
private int? _limit;
public QueryBuilder From(string table) { _table = table; return this; }
public QueryBuilder Where(string condition) { _conditions.Add(condition); return this; }
public QueryBuilder OrderBy(string field) { _orderBy = field; return this; }
public QueryBuilder Limit(int count) { _limit = count; return this; }
public string Build()
{
var sb = new StringBuilder($"SELECT * FROM {_table}");
if (_conditions.Any()) sb.Append($" WHERE {string.Join(" AND ", _conditions)}");
if (_orderBy != null) sb.Append($" ORDER BY {_orderBy}");
if (_limit.HasValue) sb.Append($" LIMIT {_limit}");
return sb.ToString();
}
}
// Usage
var query = new QueryBuilder()
.From("Orders").Where("Status = 'Active'").Where("Amount > 100")
.OrderBy("CreatedAt DESC").Limit(50).Build();
# Builder pattern in Python — fluent query construction
class QueryBuilder:
def __init__(self):
self._table = None
self._conditions: list[str] = []
self._order_by = None
self._limit = None
def from_table(self, table: str) -> "QueryBuilder":
self._table = table
return self
def where(self, condition: str) -> "QueryBuilder":
self._conditions.append(condition)
return self
def order_by(self, field: str) -> "QueryBuilder":
self._order_by = field
return self
def limit(self, count: int) -> "QueryBuilder":
self._limit = count
return self
def build(self) -> str:
sql = f"SELECT * FROM {self._table}"
if self._conditions:
sql += " WHERE " + " AND ".join(self._conditions)
if self._order_by:
sql += f" ORDER BY {self._order_by}"
if self._limit:
sql += f" LIMIT {self._limit}"
return sql
query = (QueryBuilder()
.from_table("Orders")
.where("Status = 'Active'")
.where("Amount > 100")
.order_by("CreatedAt DESC")
.limit(50)
.build())
When to use: complex object construction with many optional parameters, immutable object creation, fluent API design.
15.4 Interview Q&A
Q1: Explain the difference between Factory Method, Abstract Factory, and Builder. When would you use each?
| Pattern | Purpose | Example |
|---|---|---|
| Factory Method | Create ONE product; a condition decides the concrete type | notification_factory(NotificationType.SMS) → returns Email, SMS, or Push |
| Abstract Factory | Create FAMILIES of related products that must be consistent | ICloudFactory creates Storage + Compute + Queue together, all Azure or all AWS |
| Builder | Construct a COMPLEX object step by step | QueryBuilder().From("X").Where("Y").OrderBy("Z").Build() |
Decision framework: need to create a single object based on a condition → Factory Method. Need to create groups of related objects that must be consistent with each other → Abstract Factory. Need to construct an object with many optional parameters or a multi-step build process → Builder. Need to create a copy of an existing configured object → Prototype.
Q2: Can you explain the Singleton pattern and how you’d implement it in a modern application?
Singleton guarantees exactly one instance of a class exists for the app’s lifetime, with a single global access point — classic uses are connection pools, configuration managers, and centralized rate limiters. The classic implementation trap is thread-safety; in C# I’d use
Lazy<T>to get thread-safe lazy initialization without hand-written locks. But as an architect, I flag that a hand-rolled static Singleton is essentially global state and makes unit testing hard. In a modern .NET or Python service with a DI container, I register the type with singleton lifetime instead (services.AddSingleton<IRateLimiter, RateLimiter>()) — same one-instance guarantee, but the class depends on an abstraction and is fully mockable in tests.
Q3: Both Strategy and Factory use interfaces — how are they different?
Factory is a creational pattern — its job is to decide which object to create and hand it back; it answers “who am I working with?” Strategy is a behavioral pattern — it doesn’t care about creation at all, its job is to execute a specific algorithm; it answers “how does this work get done?” In practice I almost always use them together: a Factory picks the right Strategy based on some condition (e.g., user subscription tier), and then hands that Strategy to the service that actually executes it. For example, an
AIFactory.Create("PremiumUser")returns anIAIGenerationStrategy— maybe anOpenAIStrategyor aClaudeStrategy— and the calling service just invokes.GenerateResponseAsync()without knowing or caring which concrete strategy it got.