At some point you have probably heard someone say “we solve that with a Factory” or “that’s a Strategy”, and you were left feeling that everybody knows something you do not. It sounds like secret knowledge. It is not: it is vocabulary, and in this chapter you will see where it comes from.
What a design pattern is
A design pattern is a named solution to a problem that keeps coming back. It is not a library you install or a chunk of code you copy. It is a way of organizing classes and interfaces that many people independently found works well for a certain kind of problem.
An analogy: in a corner store, when the coffee runs out, someone says “we need to place an order”. Nobody explains each step: check the stock, call the supplier, write down the quantity. The phrase already contains them. Patterns do the same for code: instead of describing twenty lines of design, you say one word.
Where they come from
In 1994 the book Design Patterns: Elements of Reusable Object-Oriented Software came out, by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. It is known as the “Gang of Four” (GoF) book and catalogued 23 patterns. The authors did not invent them; they observed solutions that already repeated in real programs and gave them names and descriptions.
It is a valuable reference, but you do not need to read it to get started. Many of its examples are from another era, and several patterns now come built into the language, as we will see with C# and events.
What they are for
They serve two purposes:
- Communicating fast. “This code uses a Repository” tells another developer what to expect without opening a file.
- Not reinventing. Many design problems already have a known path, with its benefits and traps documented.
They are not for showing off or for decoration. A pattern is not a goal. Nobody should open a project thinking “today I’m going to use Observer”.
Problem first, pattern second
The classic beginner mistake is to learn the names and start seeing nails everywhere. You do it the other way around: write the simple code, feel a concrete pain, and then check whether a pattern exists for that pain.
Let’s look at one. This program picks a discount based on the customer type:
IDiscount discount = CreateDiscount("neighbor");
Console.WriteLine($"{discount.Apply(100m):0.00}");
static IDiscount CreateDiscount(string type)
{
if (type == "neighbor") return new PercentageDiscount(0.05m);
return new NoDiscount();
}
interface IDiscount
{
decimal Apply(decimal subtotal);
}
class PercentageDiscount : IDiscount
{
private readonly decimal _percentage;
public PercentageDiscount(decimal percentage)
{
_percentage = percentage;
}
public decimal Apply(decimal subtotal) => subtotal * (1 - _percentage);
}
class NoDiscount : IDiscount
{
public decimal Apply(decimal subtotal) => subtotal;
}
95.00
Nobody told you “use a pattern” and there is already one: CreateDiscount is a function whose only job is to decide which class to build. That is the Factory. You would have written it anyway, with another name or none. The value of knowing it is that when the if grows to ten cases and new calls are scattered across the program, you already know what the solution is called and how others do it.
The five that follow
The next five chapters cover these patterns. Here is just the problem each one addresses, so you can recognize it when you feel it:
- Factory: you build objects with
newin many places, or there is aswitchon a type to decide which one to create. The solution centralizes creation in one place. - Strategy: you have a big
iforswitchchoosing between several algorithms, like ways to calculate a discount or shipping. The solution puts each algorithm behind an interface so they can be swapped. - Observer: a change in one object must notify several parts, for example confirming an order should update stock, send an email and add loyalty points. The solution lets each part subscribe without the original object knowing them.
- Singleton: you need exactly one instance of something. It is the best known and the most abused; we give it a full chapter for its traps and for the alternative I prefer.
- Repository: your business code touches where data is stored directly, whether a list, a file or a database. The solution is an interface that hides that detail.
Notice that all five apply what we saw in SOLID: interfaces, depending on abstractions, adding without editing. Patterns are, in large part, those principles with a name attached.
When not to use a pattern
Patterns cost too, and it is the same cost as SOLID: more classes, more jumps between files. A three-line if nobody will touch does not need a factory. If the simple solution reads well and does not hurt, keep it. A pattern applied where there is no problem is exactly the “more classes is not better design” we talked about before.
One more warning: a pattern adapts. What you read in a book is the general idea, and your version in a corner store program can be shorter and different.
Exercise
For each situation, say what the problem is and which of the five patterns fits, or whether none is needed:
- When an order is confirmed you must update stock, send an email and add loyalty points, and today the
Confirmmethod calls all three classes directly. - A function that takes two prices and returns their sum.
- The checkout code has an
iffor cash, another for card and another for ATH Móvil, and it gets edited every time a payment method is added. - The order classes read and write products straight to a text file, and you want to move to a database later.
Suggested solution
- Observer. One event (the order was confirmed) must reach several parts. With Observer,
Confirmonly announces it and each part decides what to do. - None. It is a simple operation and there is no design problem to solve.
- Strategy. Each payment method is an interchangeable algorithm behind an interface, and adding one does not require editing the checkout code.
- Repository. A product interface hides whether data lives in a file or a database, and the rest of the code does not change when storage moves.
Recap
- A pattern is a named solution to a recurring problem, and it is mostly useful for communicating.
- The Gang of Four book (1994) catalogued 23; you do not need to read it to start.
- Problem first, pattern second. A pattern is not a goal.
- Every pattern costs more pieces. If the simple solution does not hurt, keep it.
- Five are coming: Factory, Strategy, Observer, Singleton and Repository.
In the next chapter we look at the first one, Factory: what happens when new calls and switch statements on a type spread through the program, and how to centralize object creation.
If you have questions, DM me on Instagram or ask in the Discord community.
