Design Patterns Overview

Expected level: Awareness

A design pattern is a named, general solution to a problem that keeps appearing in software design. It describes an approach that you adapt to your situation.

Where patterns come from

The idea was borrowed from architecture and popularised for software by the 1994 book Design Patterns by Gamma, Helm, Johnson and Vlissides, known as the “Gang of Four” (GoF) book. It describes 23 patterns in three groups. Many more have been catalogued since, covering enterprise applications, cloud systems and more.

The three classic groups

Group Concern Examples
Creational How objects are created Factory, Builder, Singleton
Structural How objects are composed Adapter, Decorator, Facade
Behavioural How objects interact Observer, Strategy, Command

A few you will see often

  • A factory creates objects in one place instead of scattering construction details around.
  • An adapter wraps an interface so that it fits what the caller expects, for example around a third-party library.
  • With an observer, objects subscribe to be told when something changes. Event handlers work this way.
  • A strategy makes an algorithm swappable, such as different pricing or sorting rules, by passing it in.
  • A singleton allows only one instance to exist. It is often overused, since it behaves like global state.

Larger-scale patterns exist too, such as Model-View-Controller, repository and, in distributed systems, retry and circuit breaker.

Using patterns sensibly

  • Learn the problem first, then the pattern. Do not force patterns into code that does not need them, because extra indirection has a cost.
  • Languages differ. First-class functions, for example, make some patterns trivial.
  • Patterns support separation of concerns and low coupling, and are often applied while refactoring.
  • An anti-pattern is a common, tempting solution that causes trouble, such as the “god class” that does everything.

Try it

Find one pattern in a codebase you work in, for example an event subscription (observer) or a function that builds objects (factory). Look it up in the Refactoring Guru catalogue and describe the problem it solves in one sentence.

Common mistakes

  • Forcing patterns into code that does not need them.
  • Overusing singletons, which behave like global state.
  • Building a god class that does everything.

Check yourself

  • What problem does an observer solve?
  • Name the three classic pattern groups and one example of each.
  • Why can a singleton cause trouble?

Related topics

Terms

Further reading