Design patterns: categories and description
Overview of design-pattern categories (creational, structural, behavioural), clear definitions of common patterns, how to recognise and draw them, syntax skeletons to remember, worked examples, common mistakes and exam guidance.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Design patterns give engineers proven, reusable ways to solve common design problems in object-oriented systems. Knowing pattern categories and their intent helps you choose the right structure (classes, interfaces, links) when you move from analysis models (use cases, sequence diagrams) to class design and implementation.
Key ideas
Start with simple definitions and assumptions.
Design pattern: a general, reusable solution to a commonly occurring problem in software design within a particular context. It is not finished code, but a template describing classes and their interactions.
- Assumptions: you are working in an object-oriented language (support for classes, objects, methods, interfaces and usually inheritance and polymorphism).
Why patterns are useful: they capture expert practice; they reduce time spent designing by giving tested structures; they improve communication (naming a pattern conveys a lot).
Categories of patterns (exact statements):
- Creational pattern: a pattern whose primary purpose is to control object creation. Assumes that choosing the right creation mechanism affects design flexibility, coupling and testability.
- Structural pattern: a pattern about how classes and objects are composed to form larger structures while keeping them flexible and efficient.
- Behavioural pattern: a pattern that describes algorithms and responsibilities between objects — how they communicate and distribute work.
The classical reference grouping is the Gang of Four (GoF) classification: the GoF book defined the above three categories and listed common patterns in each.
Important common patterns and one-line intent (define before use):
- Singleton: ensure a class has exactly one instance and provide a global access point to it.
- Abstract Factory: provide an interface to create families of related objects without specifying concrete classes.
- Prototype: create new objects by copying a prototype instance (useful when construction is expensive).
- Factory Method: define an interface for creating an object, but let subclasses decide which class to instantiate.
- Adapter: convert the interface of a class into another interface clients expect; allows classes to work together that otherwise would not because of incompatible interfaces.
- Bridge: decouple an abstraction from its implementation so that the two can vary independently.
- Composite: compose objects into tree structures to represent part–whole hierarchies; lets clients treat individual objects and compositions uniformly.
- Decorator: attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
- Facade: provide a unified high-level interface to a set of interfaces in a subsystem; makes the subsystem easier to use.
- Proxy: provide a surrogate or placeholder for another object to control access to it.
- Chain of Responsibility: pass a request along a chain of handlers; a handler either handles the request or passes it on.
- Command: encapsulate a request as an object, allowing parameterisation of clients with queues, logs, and undoable operations.
- Iterator: provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
- Observer: define a one-to-many dependency so that when one object changes state, all its dependents are notified and updated automatically.
- Strategy: define a family of algorithms, encapsulate each, and make them interchangeable.
- State: allow an object to alter its behaviour when its internal state changes; the object will appear to change its class.
- Builder: separate the construction of a complex object from its representation so that the same construction process can create different representations.
- Flyweight: use sharing to support large numbers of fine-grained objects efficiently.
- Interpreter: given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences.
- Mediator: define an object that encapsulates how a set of objects interact to reduce coupling.
- Memento: capture and externalise an object's internal state so it can be restored later without violating encapsulation.
- Template Method: define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
- Visitor: represent an operation to be performed on elements of an object structure; lets you define a new operation without changing the element classes.
How to draw pattern class diagrams (what to draw and label):
- For every pattern, draw rectangles for classes and interfaces. Label each rectangle with the class/interface name on the top line, and main responsibilities or operations on the second line if exam asks.
- Use a solid line with a closed, unfilled triangular arrowhead from subclass to superclass for inheritance (class-to-class). For a class implementing an interface (realization), use a dashed line with a hollow triangular arrowhead pointing to the interface, and mark the interface rectangle with «interface».
- Use dashed arrow labeled «use» or «depends» for dependency (e.g., a class using another in a method parameter).
- Use open diamond for aggregation and filled diamond for composition when showing part–whole (Composite pattern tasks).
- For behavioural patterns, draw sequence or communication arrows to show message flow if the question asks for interaction.
Formulas
Singleton (Java-style skeleton): class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } } — instance: the single object; applies when you need one global instance. Verify thread-safety separately.
AbstractFactory (interface sketch): interface UIFactory { Button createButton(); TextField createTextField(); } — UIFactory: factory interface to create related UI objects; use when families of products are needed.
FactoryMethod (sketch): abstract class Creator { abstract Product factoryMethod(); void operation() { Product p = factoryMethod(); p.doWork(); } } — Creator: defers product creation to subclasses.
Adapter (object adapter sketch): class Adapter implements Target { private Adaptee adaptee; Adapter(Adaptee a) { adaptee = a; } public void request() { adaptee.specificRequest(); } } — Adapter: adapts Adaptee to Target.
Composite (sketch): interface Component { void operation(); } class Leaf implements Component { void operation() { /* leaf behaviour */ } } class Composite implements Component { List<Component> children; void operation() { for c in children: c.operation(); } void add(Component c) { children.add(c); } } — Composite: uniform treatment of leaf and composite.
ChainOfResponsibility (sketch): abstract class Handler { Handler next; abstract void handle(Request r); } — Handler: passes request along chain.
Command (sketch): interface Command { void execute(); } class Invoker { Command cmd; void setCommand(Command c) { cmd = c; } void run() { cmd.execute(); } } — Command: encapsulate request as object.
Iterator (sketch): interface Iterator { boolean hasNext(); Element next(); } — Iterator: sequential access without exposing the collection.
Observer (sketch): interface Observer { void update(State s); } interface Subject { void attach(Observer o); void detach(Observer o); void notifyAllObservers(); } — Observer: publish–subscribe style.
For each skeleton above: the names are tokens to remember and apply when implementing patterns. Check thread-safety and language-specific idioms when applying (see Common mistakes).
Worked examples
Example (model answer): "Explain Singleton and draw a class diagram; discuss pros and cons and thread safety."
- Answer steps: (a) Definition: Singleton ensures one instance and global access. (b) Draw one rectangle named Singleton; mark constructor as private (write "- Singleton() private"); show a static attribute "+ instance: Singleton" and a public static method "+ getInstance(): Singleton". (c) Explain operations: getInstance creates the single instance lazily. (d) Pros: controlled access, single point for configuration/state (e.g., logger). Cons: introduces global state, hard to unit test, may hide dependencies. (e) Thread-safety: naive skeleton is not thread-safe in multithreaded programs — propose double-checked locking with a volatile instance (language-specific), or use an eager-initialised static final instance, the initialization-on-demand holder idiom, or an enum-based singleton in Java.
Example (algorithmic trace): Adapter pattern in a small program.
- Problem: Client expects interface Target.request(); existing library provides Adaptee.specificRequest().
- Classes: Target (interface), Client (calls Target.request()), Adaptee (existing), Adapter (implements Target and holds Adaptee).
- Step-by-step trace on call: (1) Client has reference t of type Target set to new Adapter(new Adaptee()). (2) Client calls t.request(). (3) Adapter.request() calls adaptee.specificRequest(). (4) Adaptee performs its work and returns result to Adapter, Adapter returns to Client.
- Draw class diagram: Client -> uses -> Target (interface); Adapter -> implements -> Target; Adapter -> has -> Adaptee (composition). Label arrows: dependency (dashed) from Client to Target, realization (dashed line with hollow triangular arrowhead) from Adapter to Target, and an association (solid line; composition if Adapter owns the Adaptee) from Adapter to Adaptee.
Example (short design problem and pattern choice): "Design a GUI toolkit supporting multiple look-and-feels (Windows, Linux)."
- Model answer: use Abstract Factory to produce families of products (Button, Menu, TextField). Draw UIFactory interface with concrete factories WindowsFactory and LinuxFactory. Client uses UIFactory to create widgets and does not depend on concrete classes. Explain benefits: adding a new OS look requires only a new concrete factory and product implementations.
Common mistakes
- Saying Singleton is always good: students forget disadvantages (global state, testing difficulty, hidden coupling) and concurrency concerns.
- Confusing Adapter and Facade: Adapter converts one interface to another for a single class; Facade provides a simplified interface to a whole subsystem.
- Overuse of inheritance where composition (object reference) should be used — many structural patterns rely on composition.
- Not specifying where responsibilities lie (which class handles what) for behavioral patterns — exam answers must assign responsibility clearly.
- Omitting thread-safety caveat for Singleton implemented with lazy instantiation.
For your exam
- Short notes: e.g., "Abstract Factory" — include definition, class-diagram sketch, use-case example, and pros/cons. Full-marks: diagram drawn with correct arrows and labels, brief explanation of applicability.
- Derivations / explanations: e.g., why choose Factory Method over Abstract Factory — explain differences in terms of object creation responsibility and extensibility.
- Programs / pseudocode: write a skeleton of a pattern (e.g., Command or Iterator). Full-marks: show interfaces and how classes interact; include brief sequence of calls.
- Diagrams: draw UML class & sequence diagrams for pattern interactions. Full-marks: correct notation (inheritance vs dependency), classes/interfaces named, main methods listed, and arrows showing message flow.
Quick check
- What is a Factory Method in one sentence?
- Draw (describe) the minimal class diagram for Adapter (what classes and arrows?).
- Name two disadvantages of using Singleton. Answers: 1) A Factory Method is a creational pattern that defines an interface for creating an object but lets subclasses decide which concrete class to instantiate. 2) Draw: rectangle Target (interface); rectangle Adapter realizes Target (dashed line with hollow triangular arrowhead from Adapter to Target); rectangle Adaptee; solid association line from Adapter to Adaptee (field). Also draw Client -> depends -> Target (dashed). 3) Disadvantages: introduces global state/hard-to-test coupling; naive lazy singleton is not thread-safe (requires special handling).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?