Introduction

In 1994, four computer scientists — Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides — published a book that would forever change how software engineers think about their problems. “Design Patterns: Elements of Reusable Object-Oriented Software” cataloged 23 recurring solutions to recurring problems in object-oriented development. The community nicknamed them the Gang of Four (GoF).

Three decades later, in a world of public cloud, hybrid architectures, Kubernetes, serverless, globally distributed teams and microservices that communicate through events, those same patterns are still a reference. Not because the world stood still. Because the fundamental problems of software have not changed — only the scale and the environment in which they appear have changed.

This article explores:

  • Why software architecture is necessary — and what happens when it is ignored
  • The origin and purpose of GoF — historical context, motivations and the structure of the 23 patterns
  • How patterns apply regardless of language — GoF is not Java, nor C++; it is a design language
  • The cloud and microservices revolution — how the classic patterns evolved and which new ones emerged
  • Development and maintenance teams — why architecture is the link that keeps systems alive for more than one generation of developers

Who this article is for: developers with hands-on experience who want to raise their problem-solving reasoning to the level of software architecture.

📦 Source code: The complete implementation for this article is in the blog-zocateli-sample repository on GitHub. Clone it, explore it and adapt it to your context.


Why Software Architecture Matters

Software without architecture: the invisible cost

Imagine a banking system built by 50 developers over 8 years, without any architectural convention. Each developer solved problems in their own way. The result is what the industry calls a Big Ball of Mud — a shapeless mass where any change can break something anywhere.

This is not a hypothetical scenario. It is the natural state of systems that grow without architectural intent. The symptoms are recognizable:

  • Invisible coupling: changing the payments module breaks the reporting module, and nobody knows why
  • Tribal knowledge: only 2 developers know how that part “really works”
  • Fear of deploying: “no deploys on Friday” became culture because nobody trusts the system
  • Constant regression: every new feature seems to bring 3 old bugs back
  • Slow onboarding: a new developer takes 6 months to become productive

Architecture is not what you do before writing code — it is the intent that guides every design decision throughout the entire life of the system.

What is software architecture, after all?

Martin Fowler defines software architecture as “the important stuff, the decisions that are hard to change” in a system. Ralph Johnson defines it as “the shared understanding that the developers have of how the system is organized”.

These definitions reveal two dimensions of architecture:

  1. Technical: modularity, coupling, cohesion, contracts between components, data flow, failure handling
  2. Social: a common vocabulary between people, conventions that allow a team of 20 to work consistently

The second dimension is frequently ignored — and that is exactly where the GoF patterns shine.

The cost of architectural technical debt

Architectural technical debt is different from, and more serious than, code-level technical debt. Refactoring a method takes an afternoon. Changing the architecture of a system in production can take months, with high risk. That is why wrong architectural decisions compound interest quickly:

1
2
3
4
Year 1: "Let's put business logic directly in the controller, it's faster"
Year 2: "We have 300 controllers with 500 lines each, impossible to test"
Year 3: "We need 6 months to migrate to anything else"
Year 4: "We can't hire seniors because nobody wants to work on this code"

Architecture does not eliminate technical debt — but it steers it and makes it visible and manageable.


The Origin of the Gang of Four

Historical context: the object-oriented software crisis

By 1994, object-oriented programming had lived through its hype peak. C++, Smalltalk and, more recently, Java promised that inheritance, encapsulation and polymorphism would solve every code reuse problem. The promise did not fulfill itself.

The problem was not object orientation itself — it was that developers had no shared vocabulary to express how to use OO tools. Every project reinvented the same solutions for the same problems. A developer experienced in Smalltalk had consolidated solutions for “how to decouple an algorithm from its concrete implementations” — but those solutions lived in their head, not in books.

Gamma, Helm, Johnson and Vlissides realized they were independently arriving at the same solutions for the same kinds of problem. The idea for the book was born at an OOPSLA conference in 1990, when Erich Gamma and Richard Helm exchanged notes about recurring patterns. Writing took 4 years.

Christopher Alexander’s influence

The authors were explicitly inspired by Christopher Alexander, an architect (of physical buildings, not software) who in 1977 published “A Pattern Language” — a catalog of 253 recurring patterns in urban and building architecture, from city design to window placement.

Alexander’s central idea: recurring problems in a context have recurring solutions that can be named, documented and communicated. When an architect says “this room needs a double-height ceiling”, every other architect knows exactly what that means — without explaining it from scratch.

GoF applied this idea to software: by saying “use a Strategy here”, you communicate an entire design structure in a single word.

The structure of a GoF pattern

Each of the 23 patterns follows a consistent format:

FieldDescription
NameThe vocabulary — “Strategy”, “Factory”, “Observer”
IntentWhat the pattern does, in one sentence
Also Known AsAlternative names
MotivationA concrete scenario that justifies the pattern
ApplicabilityWhen to use it
StructureClass diagram (UML)
ParticipantsThe classes and their responsibilities
CollaborationsHow the participants interact
ConsequencesTrade-offs — what you gain and what you give up
ImplementationImplementation notes, variations
Sample CodeC++ in the original book
Related PatternsConnections to other patterns

The Consequences field is the most ignored and the most valuable. Every pattern has a cost. Knowing the cost is what separates an architect from someone who just applies patterns mechanically.


The 23 GoF Patterns

The 23 patterns are divided into three categories, based on the kind of problem they solve:

Map of the 23 GoF patterns organized by category: Creational, Structural and Behavioral

Creational Patterns — How Objects Are Created

They encapsulate and abstract the object creation process. The goal is to decouple the code that uses an object from the code that instantiates it.

Factory Method

Defines an interface for creating an object, but lets subclasses decide which class to instantiate.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Language-independent — the principle:
// "I want to create something, but I don't want to know HOW it is created"

public abstract class NotificadorBase
{
    // Factory Method: subclasses define which channel to use
    protected abstract ICanal CriarCanal();

    public void Notificar(string mensagem)
    {
        var canal = CriarCanal();  // creation delegated to the subclass
        canal.Enviar(mensagem);
    }
}

public class NotificadorEmail : NotificadorBase
{
    protected override ICanal CriarCanal() => new CanalEmail();
}

public class NotificadorSms : NotificadorBase
{
    protected override ICanal CriarCanal() => new CanalSms();
}

// The orchestration code does not need to know which channel is used:
NotificadorBase notificador = ambiente == "prod"
    ? new NotificadorEmail()
    : new NotificadorSms();
notificador.Notificar("Order confirmed");

Abstract Factory

Creates families of related objects without specifying their concrete classes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Problem: you need components that are consistent with each other (same "family")
// Example: UI components that must all be "Light" or all "Dark"

public interface IUiFactory
{
    IBotao CriarBotao();
    IInput CriarInput();
    ICard CriarCard();
}

public class LightThemeFactory : IUiFactory
{
    public IBotao CriarBotao() => new BotaoLight();
    public IInput CriarInput() => new InputLight();
    public ICard CriarCard() => new CardLight();
}

public class DarkThemeFactory : IUiFactory
{
    public IBotao CriarBotao() => new BotaoDark();
    public IInput CriarInput() => new InputDark();
    public ICard CriarCard() => new CardDark();
}

// The screen uses the factory — it never instantiates directly:
public class TelaCheckout(IUiFactory factory)
{
    private readonly IBotao _btnConfirmar = factory.CriarBotao();
    private readonly IInput _inputCartao   = factory.CriarInput();
}

Builder

Separates the construction of a complex object from its representation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Solves the "telescoping constructor" problem:
// Instead of: new Pedido(1, "João", true, false, null, 0, "SP", "BR", ...)
// Use:

var pedido = new PedidoBuilder()
    .ParaCliente(clienteId: 1)
    .ComItem(produtoId: 10, quantidade: 2)
    .ComItem(produtoId: 15, quantidade: 1)
    .ComDesconto(10)
    .ComEnderecoEntrega("Rua A", "São Paulo", "SP")
    .ComPrioridadeExpressa()
    .Build();

public class PedidoBuilder
{
    private readonly Pedido _pedido = new();

    public PedidoBuilder ParaCliente(int clienteId)
        { _pedido.ClienteId = clienteId; return this; }

    public PedidoBuilder ComItem(int produtoId, int quantidade)
        { _pedido.Itens.Add(new Item(produtoId, quantidade)); return this; }

    public PedidoBuilder ComDesconto(decimal percentual)
        { _pedido.Desconto = percentual; return this; }

    public PedidoBuilder ComPrioridadeExpressa()
        { _pedido.Prioridade = PrioridadePedido.Expressa; return this; }

    public Pedido Build()
    {
        _pedido.Validar();  // validation centralized in Build
        return _pedido;
    }
}

Prototype

Creates new objects by copying (cloning) an existing object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Useful when creating from scratch is expensive (database query, heavy initialization)
public abstract class Componente
{
    public abstract Componente Clone();
    public string Nome { get; set; } = "";
    public Dictionary<string, string> Configuracoes { get; set; } = [];
}

public class ComponenteNginx : Componente
{
    public override Componente Clone()
    {
        var clone = (ComponenteNginx)MemberwiseClone();
        // Deep copy of the mutable settings
        clone.Configuracoes = new Dictionary<string, string>(Configuracoes);
        return clone;
    }
}

// Instead of creating and configuring from scratch every time:
var templateNginx = new ComponenteNginx { Nome = "nginx-template" };
templateNginx.Configuracoes["porta"] = "80";
templateNginx.Configuracoes["workers"] = "4";

// Cloning is much cheaper:
var nginx1 = (ComponenteNginx)templateNginx.Clone();
nginx1.Nome = "nginx-producao";

Singleton

Ensures a class has only one instance and provides global access to it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// In modern .NET, prefer dependency injection with Lifetime.Singleton
// but the pattern is still relevant to understand the concept:

// ⚠️ Thread-safe with Lazy<T> (more idiomatic in .NET):
public sealed class GerenciadorCache
{
    private static readonly Lazy<GerenciadorCache> _instancia =
        new(() => new GerenciadorCache());

    private GerenciadorCache() { }  // private constructor

    public static GerenciadorCache Instancia => _instancia.Value;

    public object? Obter(string chave) { /* ... */ return null; }
    public void Definir(string chave, object valor) { /* ... */ }
}

// Usage:
GerenciadorCache.Instancia.Definir("config", dados);

// ✅ In ASP.NET Core: use services.AddSingleton<IGerenciadorCache, GerenciadorCache>()
// The DI container guarantees the single instance with thread-safety

Structural Patterns — How Objects Are Composed

They deal with the composition of classes and objects to form larger structures while keeping flexibility and efficiency.

Adapter

Converts the interface of a class into another interface clients expect.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Classic problem: a new payment SDK with an interface different from the current one
public interface IGatewayPagamento  // interface YOUR system expects
{
    Task<ResultadoPagamento> ProcessarAsync(DadosPagamento dados);
}

// Existing third-party class with a different interface:
public class StripeClient  // you do NOT control this class
{
    public StripeResult Charge(string token, long amountCents, string currency)
        { /* Stripe SDK */ return new StripeResult(); }
}

// Adapter: adapts the Stripe interface to the interface the system expects
public class StripeAdapter(StripeClient stripe) : IGatewayPagamento
{
    public async Task<ResultadoPagamento> ProcessarAsync(DadosPagamento dados)
    {
        var resultado = await Task.Run(() =>
            stripe.Charge(dados.Token, (long)(dados.Valor * 100), dados.Moeda));

        return new ResultadoPagamento(
            Sucesso: resultado.Status == "succeeded",
            TransacaoId: resultado.Id);
    }
}

// The system never knows it is using Stripe:
IGatewayPagamento gateway = new StripeAdapter(new StripeClient());
await gateway.ProcessarAsync(dadosDoPedido);

Decorator

Adds responsibilities to an object dynamically, without changing its class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// The real power: composing behaviors without blowing up the inheritance hierarchy

public interface IRepositorioPedidos
{
    Task<Pedido?> ObterAsync(int id);
    Task SalvarAsync(Pedido pedido);
}

// Decorator 1: adds caching
public class PedidosComCache(IRepositorioPedidos inner, ICache cache)
    : IRepositorioPedidos
{
    public async Task<Pedido?> ObterAsync(int id)
    {
        var cached = await cache.GetAsync<Pedido>($"pedido:{id}");
        if (cached is not null) return cached;

        var pedido = await inner.ObterAsync(id);
        if (pedido is not null)
            await cache.SetAsync($"pedido:{id}", pedido, TimeSpan.FromMinutes(5));
        return pedido;
    }

    public Task SalvarAsync(Pedido pedido) => inner.SalvarAsync(pedido);
}

// Decorator 2: adds logging
public class PedidosComLogging(IRepositorioPedidos inner, ILogger logger)
    : IRepositorioPedidos
{
    public async Task<Pedido?> ObterAsync(int id)
    {
        logger.LogInformation("Fetching order {Id}", id);
        var result = await inner.ObterAsync(id);
        logger.LogInformation("Order {Id}: {Status}", id, result is null ? "not found" : "found");
        return result;
    }

    public Task SalvarAsync(Pedido pedido) => inner.SalvarAsync(pedido);
}

// Composition root — you stack the decorators however you want:
IRepositorioPedidos repo =
    new PedidosComLogging(
        new PedidosComCache(
            new PedidosEfCore(dbContext),
            redisCache),
        logger);

Facade

Provides a simplified interface to a complex subsystem.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Problem: completing an order involves 6 different subsystems
// Without Facade: each controller knows and orchestrates every subsystem

// With Facade: a single entry point for the use case
public class ServicoFinalizacaoPedido(
    IEstoqueService estoque,
    IFinanceiroService financeiro,
    ILogisticaService logistica,
    INotificacaoService notificacao,
    IAuditService auditoria)
{
    public async Task<ResultadoFinalizacao> FinalizarAsync(int pedidoId)
    {
        // Orchestrates the complexity internally
        await estoque.ReservarItensAsync(pedidoId);
        var cobranca = await financeiro.CobrarAsync(pedidoId);

        if (!cobranca.Aprovada)
        {
            await estoque.LiberarReservaAsync(pedidoId);
            return ResultadoFinalizacao.FalhaNoPagamento(cobranca.Motivo);
        }

        var envio = await logistica.AgendarEnvioAsync(pedidoId);
        await notificacao.NotificarClienteAsync(pedidoId, envio.PrevisaoEntrega);
        await auditoria.RegistrarAsync(pedidoId, "PEDIDO_FINALIZADO");

        return ResultadoFinalizacao.Sucesso(cobranca.TransacaoId, envio.CodigoRastreio);
    }
}

// Controller: clean, without orchestration complexity:
[HttpPost("{id}/finalizar")]
public async Task<IActionResult> Finalizar(int id)
{
    var resultado = await _servico.FinalizarAsync(id);
    return resultado.Sucesso ? Ok(resultado) : BadRequest(resultado);
}

Proxy

Provides a surrogate for another object to control access to it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Virtual proxy: loads data on demand (lazy loading)
// Protection proxy: checks permissions before delegating
// Remote proxy: abstracts network communication

// Protection proxy:
public class RepositorioPedidosProtegido(
    IRepositorioPedidos inner,
    IHttpContextAccessor httpContext) : IRepositorioPedidos
{
    public async Task<Pedido?> ObterAsync(int id)
    {
        var usuario = httpContext.HttpContext?.User;

        if (usuario?.IsInRole("Admin") != true)
        {
            // Restricts access to the user's own order
            var pedido = await inner.ObterAsync(id);
            var userId = usuario?.FindFirst("sub")?.Value;
            return pedido?.ClienteId.ToString() == userId ? pedido : null;
        }

        return await inner.ObterAsync(id);
    }

    public Task SalvarAsync(Pedido pedido) => inner.SalvarAsync(pedido);
}

Composite, Bridge, Flyweight

The remaining structural patterns solve equally common problems:

  • Composite — treats individual objects and collections uniformly (menu trees, hierarchical categories, mathematical expressions)
  • Bridge — separates abstraction from implementation so both can evolve independently (database drivers, report renderers)
  • Flyweight — efficiently shares objects that occur in large numbers (characters in a text editor, particles in games)

Behavioral Patterns — How Objects Interact

They deal with communication between objects and the distribution of responsibilities.

Strategy

Defines a family of algorithms, encapsulates each one and makes them interchangeable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Context: calculating shipping with different carriers
public interface ICalculadorFrete
{
    decimal Calcular(Endereco origem, Endereco destino, decimal pesoKg);
}

public class FreteCorreios : ICalculadorFrete
{
    public decimal Calcular(Endereco origem, Endereco destino, decimal pesoKg)
        => /* Correios logic */ pesoKg * 3.5m + 8.0m;
}

public class FreteTransportadora : ICalculadorFrete
{
    public decimal Calcular(Endereco origem, Endereco destino, decimal pesoKg)
        => /* carrier logic */ pesoKg * 2.8m + 15.0m;
}

public class FreteRetiradaLoja : ICalculadorFrete
{
    public decimal Calcular(Endereco origem, Endereco destino, decimal pesoKg)
        => 0m;  // free for in-store pickup
}

// Context: uses the strategy without knowing which one it is
public class Carrinho(ICalculadorFrete calculadorFrete)
{
    public decimal CalcularFrete(Endereco destino)
        => calculadorFrete.Calcular(_enderecoLoja, destino, _pesoTotal);
}

// Flexibility in composition:
var carrinho = new Carrinho(cliente.PrefereFreteProprio
    ? new FreteTransportadora()
    : new FreteCorreios());

Observer

Defines a one-to-many dependency between objects: when one changes state, all its dependents are notified.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Foundation for event systems, reactive programming, pub/sub
// .NET has native IObservable<T>/IObserver<T> that follow this pattern

public interface IObservadorPedido
{
    Task AoAtualizarAsync(Pedido pedido);
}

public class ServicoPedidos
{
    private readonly List<IObservadorPedido> _observadores = [];

    public void Inscrever(IObservadorPedido obs) => _observadores.Add(obs);
    public void Cancelar(IObservadorPedido obs) => _observadores.Remove(obs);

    public async Task AtualizarStatusAsync(int id, StatusPedido novoStatus)
    {
        var pedido = await _repo.ObterAsync(id);
        pedido.Status = novoStatus;
        await _repo.SalvarAsync(pedido);

        // Notifies all observers
        foreach (var obs in _observadores)
            await obs.AoAtualizarAsync(pedido);
    }
}

// Registered observers:
var servico = new ServicoPedidos(repo);
servico.Inscrever(new NotificadorEmailCliente(emailService));
servico.Inscrever(new AtualizadorEstoque(estoqueService));
servico.Inscrever(new RegistradorAuditoria(auditService));
servico.Inscrever(new GatewayWebhook(webhookService));

// In modern .NET: MediatR + domain events implement exactly this pattern

Command

Encapsulates a request as an object, allowing operations to be parameterized, queued, logged and undone.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// The Command pattern is at the heart of CQRS, event sourcing and undo/redo

public interface IComando<TResultado> { }

public record CancelarPedidoComando(int PedidoId, string Motivo)
    : IComando<ResultadoCancelamento>;

public class CancelarPedidoHandler(
    IRepositorioPedidos repo,
    IEventBus eventBus,
    IAuditService auditoria)
    : IHandlerComando<CancelarPedidoComando, ResultadoCancelamento>
{
    public async Task<ResultadoCancelamento> ExecutarAsync(CancelarPedidoComando cmd)
    {
        var pedido = await repo.ObterAsync(cmd.PedidoId)
            ?? throw new PedidoNaoEncontradoException(cmd.PedidoId);

        if (!pedido.PodeCancelar())
            return ResultadoCancelamento.Falha("Status does not allow cancellation");

        pedido.Cancelar(cmd.Motivo);
        await repo.SalvarAsync(pedido);

        // Publishes an event to other services (Observer + Command combined)
        await eventBus.PublicarAsync(new PedidoCanceladoEvent(pedido.Id, cmd.Motivo));
        await auditoria.RegistrarAsync(pedido.Id, "PEDIDO_CANCELADO", cmd.Motivo);

        return ResultadoCancelamento.Sucesso();
    }
}

Chain of Responsibility, Template Method, State, Iterator, Mediator, Visitor, Memento, Interpreter

The remaining behavioral patterns cover equally recurring problems:

PatternProblem it solvesModern use
Chain of ResponsibilityProcesses a request by passing it along a chain of handlers until it is handledASP.NET Core Middleware, pipelines
Template MethodDefines the skeleton of an algorithm in a base class, leaving parts to subclassesTest base classes, ETL pipelines
StateLets an object change its behavior when its state changesState machines, orders, workflows
IteratorTraverses a collection without exposing its internal structureIEnumerable<T>, foreach, yield return
MediatorObjects communicate through a central mediator — reduces direct dependenciesMediatR, message broker, event bus
VisitorAdds operations to objects without modifying their classesAST visitors, tree transformations
MementoCaptures and restores an object’s internal state without breaking encapsulationUndo/redo, checkpoints, snapshots
InterpreterDefines a grammar and an interpreter for itDSLs, business rule validation

GoF Is Language-Independent

A common misconception is treating the GoF patterns as “Java patterns” or “C++ patterns”. The original book was written with examples in C++ and Smalltalk. But the patterns are design concepts, not APIs.

The same problem, different languages

Observer in JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Node.js EventEmitter is a native Observer
const { EventEmitter } = require('events');
class ServicoPedidos extends EventEmitter {
  async cancelar(id, motivo) {
    /* ... */
    this.emit('pedidoCancelado', { id, motivo });
  }
}
const svc = new ServicoPedidos();
svc.on('pedidoCancelado', ({ id }) => notificarCliente(id));
svc.on('pedidoCancelado', ({ id }) => atualizarEstoque(id));

Strategy in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from abc import ABC, abstractmethod

class CalculadorFrete(ABC):
    @abstractmethod
    def calcular(self, peso: float) -> float: ...

class FreteCorreios(CalculadorFrete):
    def calcular(self, peso: float) -> float:
        return peso * 3.5 + 8.0

class Carrinho:
    def __init__(self, calculador: CalculadorFrete):
        self._calculador = calculador  # injected Strategy

Factory in Go:

1
2
3
4
5
6
7
8
9
type Notificador interface { Enviar(msg string) error }

func NovoNotificador(tipo string) Notificador {
    switch tipo {
    case "email": return &NotificadorEmail{}
    case "sms":   return &NotificadorSms{}
    default:      return &NotificadorLog{}
    }
}

Why does this matter in cross-functional teams?

When you have a team with C#, Go, Python and TypeScript developers, the GoF patterns are the lingua franca of design. The conversation:

“We need an Observer here, because several modules need to react when the order status changes”

…makes sense to everyone, regardless of the language each person uses day to day. Without this common vocabulary, the conversation would be:

“We need a class that, when the status changes, calls a list of other classes that have a method that… you get it”


The Cloud and Microservices Era

How the cloud changed the context, not the problems

Moving to the cloud brought new problems of scale, availability and distribution. But the fundamental problems — coupling, cohesion, separation of concerns — did not change. What changed was where the problems appear and how much a bad decision costs.

EraEnvironmentCost of failureScaleCore pattern
MonolithSingle serverContainedVerticalClassic GoF
SOAInternal networkModerateModerateAdapter, Facade
MicroservicesDistributed cloudHigh (cascading)Unlimited horizontalDistributed patterns
ServerlessEphemeral cloudVariableAuto-scalingStateless by design
HybridMixedComplexHeterogeneousInfrastructure abstraction

Timeline of software architecture evolution: Monolith, SOA, formalized GoF, Cloud Native and Hybrid

New patterns for new problems

The cloud brought a new generation of patterns, many of them built on GoF principles:

Circuit Breaker — the Proxy applied to external calls. It detects cascading failures and stops calls to degraded services:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// Polly implements Circuit Breaker in .NET:
var pipeline = new ResiliencePipelineBuilder()
    .AddCircuitBreaker(new CircuitBreakerStrategyOptions
    {
        FailureRatio = 0.5,          // 50% failures → opens the breaker
        SamplingDuration = TimeSpan.FromSeconds(30),
        BreakDuration = TimeSpan.FromSeconds(15),
        OnOpened = args =>
        {
            logger.LogWarning("Circuit breaker OPEN for the payments service");
            return ValueTask.CompletedTask;
        }
    })
    .Build();

await pipeline.ExecuteAsync(async ct =>
    await gatewayPagamentos.ProcessarAsync(dados, ct));

Sidecar — the Decorator applied at the infrastructure level. An auxiliary process that runs next to the main service, adding responsibilities (logging, mTLS, rate limiting) without changing the service code:

1
2
3
4
5
6
7
8
9
# Kubernetes: logging sidecar (Decorator pattern at pod level)
spec:
  containers:
  - name: api-pedidos          # main container
    image: api-pedidos:1.2
  - name: fluent-bit           # sidecar: collects and ships logs
    image: fluent/fluent-bit
    volumeMounts:
    - mountPath: /var/log/pods

Saga — Command + Observer applied to distributed transactions. Since there is no ACID transaction across microservices, the Saga orchestrates a sequence of local transactions with compensations for failures:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Saga orchestrated with MassTransit:
// 1. Reserve stock            → on failure → compensate: nothing
// 2. Charge payment           → on failure → compensate: release reservation
// 3. Schedule shipping        → on failure → compensate: refund + release
// 4. Notify customer          → on failure → compensate: log (not critical)

public class FinalizarPedidoSaga : MassTransitStateMachine<FinalizarPedidoState>
{
    public State Reservando { get; private set; } = null!;
    public State Cobrando { get; private set; } = null!;
    public State Enviando { get; private set; } = null!;

    public FinalizarPedidoSaga()
    {
        Initially(
            When(PedidoFinalizado)
                .Then(ctx => ctx.Saga.PedidoId = ctx.Message.PedidoId)
                .TransitionTo(Reservando)
                .Publish(ctx => new ReservarEstoqueCommand(ctx.Saga.PedidoId)));

        During(Reservando,
            When(EstoqueReservado)
                .TransitionTo(Cobrando)
                .Publish(ctx => new CobrarPagamentoCommand(ctx.Saga.PedidoId)),
            When(EstoqueFalhou)
                .Publish(ctx => new PedidoCanceladoEvent(ctx.Saga.PedidoId, "Out of stock"))
                .Finalize());
        // ...
    }
}

CQRS (Command Query Responsibility Segregation) — Command + Strategy applied to reads/writes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Segregating reads from writes allows independent optimizations
// Writes: strong consistency, validations, domain events
// Reads: denormalization, cache, read replicas, projections

// Command side (writes):
public record CriarPedidoCommand(int ClienteId, List<ItemDto> Itens)
    : ICommand<PedidoCriadoResult>;

// Query side (reads — no domain entities, straight to the read database):
public record ListarPedidosQuery(int ClienteId, int Pagina)
    : IQuery<PagedResult<PedidoResumoDto>>;

public class ListarPedidosHandler(IReadDbContext db)
    : IQueryHandler<ListarPedidosQuery, PagedResult<PedidoResumoDto>>
{
    public async Task<PagedResult<PedidoResumoDto>> HandleAsync(ListarPedidosQuery q)
        => await db.PedidosView  // denormalized view, optimized for reads
            .Where(p => p.ClienteId == q.ClienteId)
            .OrderByDescending(p => p.DataCriacao)
            .ToPagedResultAsync(q.Pagina);
}

Cloud vs On-Premises: the most expensive architectural decision

The cloud vs on-premises dichotomy is not technical — it is strategic and has deep architectural implications:

DimensionCloudOn-PremisesHybrid
ScalabilityElastic (pay per use)Limited by hardwareBurst to cloud
LatencyDepends on the regionPredictable, lowRouting complexity
ComplianceVaries by cloud/regionFull control of dataSensitive data: on-prem
CapEx vs OpExOpEx dominantCapEx dominantMixed
Vendor lock-inHigh (PaaS/SaaS)LowModerate
Ops complexityLow (managed)High (infra team)Very high
Supporting patternsAdapter (abstract the cloud SDK)Not neededAnti-Corruption Layer

Adapter as anti-lock-in: teams that build directly on cloud providers throughout the code get stuck. The solution is to use the Adapter pattern to abstract the infrastructure:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ❌ Direct lock-in to Azure:
public class PedidoService
{
    private readonly BlobServiceClient _blob;   // direct Azure SDK
    private readonly ServiceBusClient _bus;     // direct Azure SDK

    public async Task ProcessarAsync(Pedido p)
    {
        await _blob.GetBlobContainerClient("pedidos")
            .UploadBlobAsync(p.Id.ToString(), /* ... */);
        await _bus.CreateSender("pedidos").SendMessageAsync(/* ... */);
    }
}

// ✅ With abstraction (Adapter + Facade):
public class PedidoService(IArmazenamento storage, IFilaMensagens fila)
{
    public async Task ProcessarAsync(Pedido p)
    {
        await storage.SalvarAsync("pedidos", p.Id.ToString(), p);
        await fila.PublicarAsync("pedidos", new PedidoCriadoEvent(p.Id));
    }
}

// Implementations can be swapped without touching the service:
// services.AddSingleton<IArmazenamento, AzureBlobStorage>();
// services.AddSingleton<IArmazenamento, S3Storage>();
// services.AddSingleton<IArmazenamento, LocalFileSystem>(); // dev/test

Development Teams and Maintenance Teams

This is perhaps the most underestimated dimension of software architecture. Every successful system ends up being maintained by people who did not build it. Sometimes by a different team. Sometimes years later. Sometimes by developers with very different profiles and skills.

The real lifecycle of a system

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Phase 1 — Construction (6-18 months):
  Original team: motivated seniors, deep domain knowledge
  Focus: delivery speed, features, go-to-market
  Risk: fast decisions without documenting trade-offs

Phase 2 — Growth (1-3 years):
  Team: mix of original + new members
  Focus: scaling teams, keeping velocity
  Risk: pattern divergence, "knowledge islands"

Phase 3 — Maturity (3-10 years):
  Team: mostly maintenance, few originals
  Focus: stability, fixes, small improvements
  Risk: "nobody knows why this code exists"

Phase 4 — Legacy (10+ years):
  Team: maintenance, possibly offshore
  Focus: keep it running without breaking
  Risk: forced rewrite due to accumulated technical debt

Why patterns are the system’s institutional memory

When a new developer arrives at a system that uses the GoF patterns consistently, they do not need to reinvent how to read the code. On seeing IStrategy as a dependency injected into a class, they immediately understand:

  1. This class has behavior that can vary
  2. The implementations are in other files, named XXXStrategy
  3. To add a new behavior, just create a new implementation
  4. Existing code does not need to change (Open/Closed Principle)

Without this shared vocabulary, the same scenario produces:

“Why is there an interface here with only one implementation? This looks like waste.”

…followed by a well-intentioned refactoring that removes the abstraction, creating coupling, making other code harder to test, and breaking behavior in production.

Team diversity: an asset with a coordination cost

Modern software teams are cross-functional by necessity:

RoleMain focusArchitecture perspective
Backend DeveloperBusiness logic, APIsDomain patterns, CQRS, Event Sourcing
Frontend DeveloperUX, rendering performanceComponent patterns, global state
Data EngineerPipelines, ETL, analyticsData patterns, streaming
DevOps / SREAvailability, observabilityInfra patterns, resilience
Solutions ArchitectIntegration, domainEnterprise patterns, bounded contexts
Tech Lead / Staff EngPlatform decisionsAll levels
L1/L2 SupportTriage, quick fixesMaintainability patterns

The risk of teams without a common language:

  • A Data Engineer implements a pipeline with business logic that duplicates what already exists in the domain
  • A DevOps engineer creates deploy scripts that assume implementation details the backend team has changed
  • L2 support fixes a bug in the Adapter without understanding there are multiple implementations, breaking another one

Documented architecture — with named patterns, decision records (ADRs) and context diagrams — is what allows people with different perspectives to contribute without collision.

Architecture Decision Records (ADRs)

For each relevant architectural decision, document:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# ADR-007: Using the Strategy pattern for shipping calculation

**Status:** Accepted  
**Date:** 2025-03-15  
**Context:** Shipping calculation must support multiple carriers,
with the ability to add new ones without changing existing code.

**Decision:** Implement using the Strategy pattern with dependency injection.
Strategy selection will happen in the composition root based on configuration.

**Consequences:**
- ✅ Adding a new carrier = creating a new class, without changing existing code
- ✅ Each strategy is testable in isolation
- ✅ The selection rule is explicit and centralized
- ⚠️ More classes in the project (acceptable, each has a clear responsibility)
- ❌ Do not use: when there is only one way to calculate and no prospect of change

**Related patterns:** Factory Method (to create the right Strategy), Open/Closed Principle

That record is worth gold to the maintenance team 3 years later. Without it, the question “why is this interface here?” has no answer — and the improvised answer is usually wrong.


Principles That Underpin Everything

The GoF patterns do not exist in a vacuum. They are practical expressions of more fundamental principles. The most important ones:

SOLID

PrincipleDefinitionGoF pattern that expresses it
S — Single ResponsibilityOne class, one reason to changeFacade (isolates responsibilities), Command
O — Open/ClosedOpen for extension, closed for modificationStrategy, Decorator, Observer
L — Liskov SubstitutionSubclasses must be substitutable for their basesFactory Method, Template Method
I — Interface SegregationSmall, focused interfacesAdapter, Proxy
D — Dependency InversionDepend on abstractions, not on implementationsAll patterns via DI

Cohesion and Coupling

High cohesion, low coupling — perhaps the oldest and most violated principle of software engineering.

  • High cohesion: each module/class does one thing well. Facade, Strategy and Command promote cohesion.
  • Low coupling: modules have few dependencies on each other. Observer, Mediator and Event Bus reduce coupling.

Law of Demeter (Principle of Least Knowledge)

A module should know only its immediate collaborators — not the collaborators of its collaborators.

1
2
3
4
5
6
7
// ❌ Violates Demeter — "train wreck code"
// The service knows the internal structure of 4 different objects:
var cidade = pedido.Cliente.Endereco.Cidade.Nome;

// ✅ Respects Demeter — add a method to the responsible object:
var cidade = pedido.ObterCidadeEntrega();
// "Take only one step at a time"

Pitfalls: When Patterns Get in the Way

Patterns applied without judgment are as harmful as no patterns at all. The most common anti-patterns:

Overengineering (“patternitis”)

1
2
3
4
5
6
7
// ❌ Factory for a single implementation that will not change:
public interface ICalculadorImposto { decimal Calcular(decimal valor); }
public class CalculadorImpostoFactory { public ICalculadorImposto Criar() => new CalculadorImposto(); }
public class CalculadorImposto : ICalculadorImposto { public decimal Calcular(decimal v) => v * 0.12m; }

// ✅ When there is only one implementation and no expected change:
public static decimal CalcularImposto(decimal valor) => valor * 0.12m;

Singleton as a global variable

Singleton is the most abused pattern. When everything is a Singleton, you essentially recreate global state:

1
2
3
4
5
6
7
8
9
// ❌ Singleton as global access (hinders testing, hides dependencies):
var db = DatabaseSingleton.Instancia;       // global coupling
var cache = CacheSingleton.Instancia;       // impossible to test in isolation
var config = ConfigSingleton.Instancia;     // changes silently affect the whole app

// ✅ Singleton managed by the DI container (testable, replaceable):
services.AddSingleton<IDatabaseContext, DatabaseContext>();
services.AddSingleton<ICache, RedisCache>();
// In tests: AddSingleton<ICache, InMemoryCache>()

Premature abstraction

Do not use patterns for problems you do not have yet:

“You Aren’t Gonna Need It” (YAGNI) — do not add complexity for hypothetical needs.

The rule of thumb: when the problem appears for the second time, consider a pattern. When it appears for the third time, apply it.


Conclusion

The GoF patterns are turning 30 and remain on the required reading list of software engineers around the world — not out of nostalgic reverence, but because the problems they solve have not disappeared. Naming solutions to recurring problems is one of the most powerful tools in engineering.

What changed were not the fundamental problems, but the context in which they appear:

  • In a monolith, a poorly applied Observer produces code that is hard to read. In a distributed system, it produces a cascade of failures that takes down multiple services.
  • In a one-developer project, a Singleton without DI is an annoyance. In a team of 50 people, it creates hidden dependencies nobody sees until the system goes down in production.
  • In a static on-premises environment, coupling to a specific implementation is manageable. In the hybrid cloud ecosystem, it creates migration debt measured in months.

Software architecture — especially its named patterns — is what allows systems to survive beyond their original generation of developers. It is what lets a developer who joins a project today understand the design intentions of whoever built the system 5 years ago. It is what lets the maintenance team fix a bug without accidentally introducing three new ones.

Learn the 23 GoF patterns. Not to apply all of them — but to have a vocabulary that lets you think, communicate and document design decisions precisely. Someone will maintain tomorrow the software you write today. Leave clear messages.


Read Also


References