Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 57 ยท Getting Started with Design

What Are Design Patterns?

Learn what design patterns are, where they come from, how they differ from algorithms and frameworks, when they hurt, and how to read a pattern description.

Every programmer eventually writes the same kind of code twice. A class that must have only one instance. A way to let many parts of a program react when something changes. A wrapper that makes one interface look like another. After enough projects you notice that the problem keeps coming back, and that a handful of solutions work well again and again.

A design pattern is a named, reusable solution to a common design problem in a specific context. It is not a finished piece of code you paste in. It is a description of a structure (which classes exist, who talks to whom) together with the reasons it works and the costs it brings. The name matters as much as the structure: saying "let's use a strategy here" tells your teammates in four words what would take a paragraph otherwise.

This track teaches the classic patterns, the principles behind them, and how to use them in low-level design (LLD) problems and interviews. Examples are written in JavaScript so you can run them right on the page, and the lessons show the Java, C++ and Python flavors where they differ.

Java and C++ pattern snippets in this track are read-only fragments that show structure. The runnable examples are JavaScript stand-ins that follow the same structure, and each lesson says what is the real language feature and what is the stand-in.

What a pattern really is

A named solution A proven way to organize classes for a recurring problem.
A shared vocabulary One word replaces a long explanation.
A trade-off Every pattern gains something and costs something.
1 / 2

Where patterns come from

The idea started in architecture. In the 1970s the architect Christopher Alexander described recurring solutions to problems in buildings and towns, each with a name, a context and a reasoning. Software developers borrowed the format.

In 1994 four authors, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, published Design Patterns: Elements of Reusable Object-Oriented Software. They are known as the Gang of Four (GoF), and the book catalogs 23 patterns in three families:

  • Creational patterns control how objects are made (Singleton, Factory Method, Builder).
  • Structural patterns control how objects are combined into larger structures (Adapter, Decorator, Composite).
  • Behavioral patterns control how objects share work and communicate (Strategy, Observer, Command).

The GoF book is old, and the examples were C++ and Smalltalk. The patterns survived because they describe object-oriented thinking rather than any one language. Since then the community added more patterns for architecture, concurrency and distributed systems, and this track covers the popular ones too.

Anatomy of a pattern

Almost every pattern description has the same parts. Learning to read them is half of learning the pattern.

Part Question it answers
Name What do we call it?
Intent What does it do, in one sentence?
Problem What goes wrong without it?
Solution Which participants exist and how do they collaborate?
Structure What does the class diagram look like?
Consequences What do we gain, and what do we pay?
Related patterns What is it often confused with or combined with?

Notice the consequences row. A pattern with only benefits is a sales pitch. Patterns usually add classes, indirection and files, and in return they make one kind of change cheap. Whether that is a good deal depends on whether that kind of change will actually happen in your code.

A problem worth solving

Here is the kind of code that makes people reach for a pattern. A shop calculates shipping with a chain of conditions. Run it first.

JS Before: a conditional that keeps growing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This works. It is also a design problem waiting to happen. Each new delivery method means editing shippingCost, and every edit risks breaking the other branches. Discounts, regional rules and carrier APIs will all want to live inside this one function. The problem is that a family of interchangeable behaviors is hard-wired into one place.

The same code with a pattern

The pattern that fits is Strategy: put each behavior behind a common interface and let the caller pick one. In JavaScript the interface can be as small as "an object with a cost function".

JS After: one object per shipping method

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output for the three old methods is identical, but now shippingCost never changes when a method is added. That is the benefit. The cost is a lookup table and a bit more structure. For three methods that is a close call; for fifteen methods, each with its own rules and tests, it is clearly worth it.

In Java the same idea is written with an interface and one class per strategy. This snippet is read-only; it shows the structure without a runnable program around it.

Java
interface ShippingStrategy {
    double cost(double weightKg);
}

class StandardShipping implements ShippingStrategy {
    public double cost(double weightKg) { return 4 + weightKg * 0.5; }
}

class ExpressShipping implements ShippingStrategy {
    public double cost(double weightKg) { return 10 + weightKg * 1.2; }
}

The C++ version uses a base class with a virtual function:

C++
struct ShippingStrategy {
    virtual ~ShippingStrategy() = default;
    virtual double cost(double weightKg) const = 0;
};

struct StandardShipping : ShippingStrategy {
    double cost(double weightKg) const override { return 4 + weightKg * 0.5; }
};

Same pattern, three languages, very different amounts of ceremony. That is a theme of this whole track.

Pattern, algorithm or framework?

Beginners often mix up three ideas.

  • An algorithm is a precise recipe for a computation, such as binary search. Two programmers implementing it end up with nearly identical steps. A pattern is looser: two implementations of Observer can look quite different.
  • A framework is code you build on. It calls your code and gives you a ready-made structure. Frameworks often use patterns internally (a web framework's middleware is a chain of responsibility), but a framework is a product and a pattern is an idea.
  • A principle such as the Single Responsibility Principle is a guideline about quality. Patterns are concrete structures that often result from following principles. You will meet the principles in the next chapter.

What patterns give you

Used where they fit, patterns pay off in several ways.

  • Shared vocabulary. "Make that an Observer" replaces five minutes of explanation, which makes design reviews and planning faster and helps teammates collaborate.
  • Reusable, proven solutions. You start from a design that many people have already tested, instead of re-inventing it and hitting the same bugs.
  • Easier change. Most patterns put a seam where requirements are likely to move, so new behavior arrives as new code rather than edits to old code. That helps maintainability and extensibility.
  • Better testability. Patterns built on interfaces (Strategy, Factory, Dependency Injection) let tests substitute fakes.
  • Simpler complex problems. Splitting a tangled problem into named roles (subject and observers, context and states) makes each part small enough to reason about.
  • Scalability of the code base. Clear roles and loose coupling let a team grow without everyone editing the same classes.

Trade-offs of the three families

Each family of the Gang of Four catalog buys something and costs something.

Family What it gives you Typical cost
Creational Flexibility in how objects are made, central control over creation More classes and indirection, hidden dependencies (Singleton), overhead for simple objects
Structural Objects that fit together and share work: easier reading of composed systems, reuse Added layers, a risk of over-engineering, maintenance overhead when a wrapper chain grows
Behavioral Clear responsibilities and loose coupling between collaborating objects Behavior spread over many small classes, harder to follow a flow, notification chains that surprise you

Every pattern also has its own limitations: Singleton hides global state, Factory Method multiplies subclasses, Strategy needs clients that know which strategy to pick, Dependency Injection adds a wiring step. Their lessons name these costs, and the next section collects the general ways to go wrong.

When patterns hurt

Patterns have a bad reputation in some teams, and it is earned by misuse.

  1. Pattern fever. A beginner learns Factory and Singleton and wraps everything in them. The code gets longer without getting easier to change.
  2. Solving a problem you do not have. Adding a PaymentStrategyFactory for the one payment provider you will ever use is speculation. The usual advice is the rule of three: wait until you see the third similar case before abstracting.
  3. Fighting the language. Many GoF patterns exist to work around missing features of 1990s C++ and Java. In a language with first-class functions, a Command is often just a function and a Strategy is often just a callback. See patterns across languages.
  4. Hiding simple logic. Three lines of code are easier to read than four classes. Indirection has a reading cost.
  5. Tight deadlines and misapplication. Picking a pattern because it sounds right, not because it matches the problem, produces the worst of both worlds: the structure of the pattern without its benefit. Under time pressure the simple version usually wins.
  6. Lack of relevance. Some problems simply have no pattern. That is fine; patterns are not a checklist to complete.

A good rule: start with the simplest code that works, notice where change keeps hurting, and then apply the pattern that makes that change cheap.

How to learn a pattern well

When you study each pattern in this track, ask the same five questions:

  1. What change is this pattern designed to make easy?
  2. What does the simplest version look like in my language?
  3. What does it cost (extra classes, indirection, harder debugging)?
  4. Which pattern looks similar, and what is the real difference?
  5. How would I test it?

Question 4 is the one that separates people who memorized names from people who understand them. Strategy and State have nearly the same class diagram, yet one is chosen by the caller and the other changes itself. You will practice these comparisons throughout the track.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which description best fits a design pattern?

    A pattern describes structure and reasoning, and it is not code you install. Algorithms are exact recipes, libraries are products, and rules are principles.
  2. 2. What does GoF stand for, and what did that group publish?

    Gamma, Helm, Johnson and Vlissides published Design Patterns in 1994 with 23 patterns in creational, structural and behavioral families.
  3. 3. In the shipping example, what was the main benefit of the Strategy version?

    The benefit is cheap extension: new behavior is added as a new object. It is not about speed or memory, and tests are still needed.
  4. 4. A teammate adds a factory, an interface and three classes for something that has only one implementation and is unlikely to change. What is this called?

    Abstracting before a real need appears adds indirection without benefit. The rule of three suggests waiting for the third similar case.

Summary

  • A design pattern is a named, reusable solution to a recurring design problem, described with its intent, structure and consequences.
  • The Gang of Four book (1994) cataloged 23 patterns in creational, structural and behavioral families.
  • Patterns are different from algorithms (exact recipes), frameworks (code you build on) and principles (quality guidelines).
  • Every pattern trades extra structure for cheaper change in one direction; judge whether that change will really happen.
  • Misuse includes pattern fever, speculative abstraction, fighting the language and hiding simple logic.
  • Study each pattern by asking what change it eases, its simplest form, its cost, its look-alikes and how to test it.

Next, learn the drawing language used to describe patterns: Reading and Drawing UML for Low-Level Design.