A pattern is not a snippet of code to copy but a description of a solution: when it fits, what problem it solves, what it gives you and where it is awkward. Once a solution has a name, a team can agree briefly, “let’s use an observer here”, instead of retelling how it works at length.
Categories from the Gang of Four book
| Group | What it describes | Examples |
|---|---|---|
| Creational | creating objects when a hard-coded constructor call is inconvenient | factory method, singleton, builder |
| Structural | composing classes and objects into larger structures | adapter, decorator, facade, proxy |
| Behavioural | distributing responsibilities and the interaction between objects | observer, strategy, command, iterator |
How a pattern is structured and when to use it
- Context and problem: the situation in which the problem arises, for example when you need a single object in the system that is available from everywhere.
- Solution: a diagram of classes and interactions, showing who creates whom and who is notified about what.
- Consequences: what the solution gives you and what you pay for it, such as flexibility against more code and indirection.
A pattern is appropriate when the problem really recurs and is expected to change in the way the pattern describes. Building one in “just in case” leads to excess code: if the system will never have a second storage implementation, an abstract factory over it solves a problem that does not exist.
Example: observer
One object sends notifications to everyone who has subscribed, without knowing anything about how they work. Event subscriptions and reactive libraries are built on this idea.
class Subject: def __init__(self): self._observers = [] def attach(self, observer): self._observers.append(observer) def notify(self, event): for observer in self._observers: observer(event)Where the term comes from
The idea was brought over from the architecture of buildings: in the 1970s Christopher Alexander described recurring solutions to design problems and called them patterns. In programming it was developed by Kent Beck and Ward Cunningham, who in 1987 presented a pattern language for object-oriented programs at the OOPSLA conference. The subject became widely known after the 1994 book “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, the “Gang of Four”. The book contains 23 patterns, which are still called the GoF patterns.
Sources
the term is written from these pages- Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley (страница книги, informIT)informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610(opens in a new tab)
- Hillside Group — об истории и устройстве паттерновhillside.net/index.php/patterns/about-patterns(opens in a new tab)
Verified 9 Nov