Skip to content
Back to blog
Design Patterns

Design Patterns: Beyond the Definitions

Updated 22 min read

Design patterns are more than reusable code structures. Learn the problems they solve, the trade-offs they introduce, and how to decide when a pattern improves your software design—and when a simpler solution is better.

Table of Contents


Introduction

Imagine you are building an order processing system.

Initially, the application supports one payment provider. The implementation is straightforward:

typescript
async function processPayment(
  orderId: string,
  amount: number,
): Promise<void> {
  await stripeClient.charge({
    orderId,
    amount,
  });
}

The function is easy to understand. It has a clear purpose, and there is little abstraction to navigate.

A few months later, the business decides to support another payment provider. Then it needs to handle different payment methods, retry certain failures, record transaction results, and route payments according to customer preferences.

The original function starts to grow.

typescript
async function processPayment(
  orderId: string,
  amount: number,
  provider: string,
): Promise<void> {
  if (provider === "stripe") {
    await stripeClient.charge({
      orderId,
      amount,
    });
  } else if (provider === "paypal") {
    await paypalClient.createPayment({
      orderId,
      amount,
    });
  } else if (provider === "bank_transfer") {
    await bankClient.transfer({
      orderId,
      amount,
    });
  } else {
    throw new Error("Unsupported payment provider");
  }
}

This implementation is not automatically wrong. For a small application with a few stable options, it may be entirely reasonable.

The concern emerges as the system evolves.

Adding a provider requires modifying the existing function. Each provider may have different parameters, error semantics, authentication requirements, and response formats. The function gradually becomes responsible for decisions that belong to different parts of the system.

At this point, a design question appears:

Should we introduce an abstraction that allows payment providers to be handled independently?

That question leads naturally to patterns such as Strategy, Adapter, and Factory.

But notice the order of reasoning. We did not start by deciding to use a pattern. We started by identifying a problem and asking how the design should change.

This distinction is the foundation of understanding design patterns.

1. What Problem Do Design Patterns Actually Solve?

Software requirements change. The difficulty is not simply implementing those changes, but doing so without making the rest of the system increasingly fragile.

A design pattern provides a reusable approach to a recurring design problem. It helps organize responsibilities, relationships, or object interactions in a way that addresses a particular source of complexity.

However, not every problem requires a pattern.

1.1 The difference between a coding problem and a design problem

A coding problem concerns the implementation of a particular operation.

For example, calculating a discount may require a formula, a condition, or a loop.

A design problem concerns how responsibilities and dependencies should be organized as the system grows.

Consider two discount rules:

typescript
function calculateDiscount(
  amount: number,
  isPremium: boolean,
): number {
  return isPremium ? amount * 0.9 : amount;
}

This function is small, explicit, and easy to test. There is no compelling reason to introduce a collection of classes merely because the function contains a conditional expression.

Now imagine a commerce platform with dozens of discount policies. Some depend on customer segments, others depend on campaigns, product categories, or external eligibility services. Policies may be configured independently, and new policies are introduced regularly.

The problem is no longer just calculating a number. It is deciding how discount policies are represented, selected, tested, and extended.

A Strategy Pattern implementation might now be useful.

The distinction is important:

A conditional statement is a code construct. A growing collection of independently changing behaviors is a potential design problem.

Patterns are generally more valuable when they address the second situation.

1.2 Design patterns help manage change

A useful way to evaluate a design is to ask what happens when a requirement changes.

Suppose a system supports three payment providers.

When adding a fourth provider, do you need to modify a large function that handles every provider? Do you need to change multiple unrelated modules? Or can you implement the new provider behind an existing contract and register it with the application?

The last option may be easier to maintain because it localizes the change.

However, that does not mean every design should be optimized for hypothetical future extensions. Additional abstractions also create code that must be understood, tested, and maintained.

A good design considers both the likelihood of change and the cost of accommodating it.

1.3 Patterns organize relationships, not just code

It is easy to think of a design pattern as a collection of classes.

For example, the Strategy Pattern is often illustrated using an interface and several implementing classes.

But the interface is not the real point.

The important idea is that a component can use a behavior without depending on the concrete implementation of that behavior.

Likewise:

  • Factory patterns separate object creation decisions from their use.
  • Observer organizes relationships between event producers and interested consumers.
  • Decorator allows behavior to be composed around an existing object.
  • Adapter makes incompatible interfaces work together.
  • State represents behavior that varies according to an object's current state.

The code structures differ, but the deeper question remains the same: what relationship or responsibility are we trying to make easier to manage?

2. From Code That Works to Code That Can Change

A common mistake in software design is to treat working code as evidence of good design.

Working code is necessary, but it is not sufficient.

A function can produce correct results today while making every future modification increasingly expensive.

2.1 A design can be simple and still become difficult to maintain

Consider an order service:

typescript
type PaymentMethod =
  | "stripe"
  | "paypal"
  | "bank_transfer";

async function payOrder(
  method: PaymentMethod,
  orderId: string,
  amount: number,
): Promise<void> {
  switch (method) {
    case "stripe":
      await stripeClient.charge({
        orderId,
        amount,
      });
      break;

    case "paypal":
      await paypalClient.createPayment({
        orderId,
        amount,
      });
      break;

    case "bank_transfer":
      await bankClient.transfer({
        orderId,
        amount,
      });
      break;
  }
}

This is understandable. There is nothing inherently wrong with a switch statement.

But suppose provider selection is now needed in several places:

  • Order checkout.
  • Subscription renewals.
  • Refund processing.
  • Marketplace payouts.
  • Administrative transaction tools.

If each location contains its own provider-specific conditions, the same decision may be duplicated across the application.

A new provider could require changes in several modules, and one of those locations may be forgotten.

The problem is not that the code uses switch. The problem is that a decision that should have one clear owner is being repeated across the system.

2.2 Identify the source of coupling

Coupling describes how strongly one part of a system depends on another.

Some coupling is unavoidable. A payment operation must depend on some mechanism capable of processing payments.

The design question is whether the dependency is appropriate and whether its details spread farther than necessary.

In the example above, the order service knows about specific providers and their different APIs. That means provider-specific implementation details are part of its responsibility.

If the system needs to support new providers frequently, this relationship may become expensive to maintain.

One possible improvement is to define a stable payment contract and implement each provider separately.

typescript
interface PaymentGateway {
  charge(
    orderId: string,
    amount: number,
  ): Promise<void>;
}

The interface describes what the application needs, rather than how a specific provider performs the operation.

This does not solve every payment integration problem. Real providers may require different workflows, idempotency mechanisms, refund semantics, or asynchronous confirmation. Those differences may need additional abstractions.

Nevertheless, the contract gives us a place to begin separating the application from provider-specific details.

2.3 Design for meaningful variation

A useful design question is:

Which parts of this system change independently?

If every payment provider changes independently, each may deserve its own implementation.

If all providers are stable and the system is unlikely to add more, separate implementations may provide little value.

The same reasoning applies to logging, caching, notification delivery, pricing rules, and authentication mechanisms.

Do not create abstractions merely because two pieces of code look different. Look for a meaningful boundary where behavior, responsibility, or change can be isolated.

That is the point at which a design pattern may become useful.

3. Understanding the Idea Behind a Pattern

Before applying a pattern, it helps to understand the design decision it represents.

A useful mental model is to think of a pattern as a response to a recurring question.

Design questionPattern to investigateUnderlying idea
How can behavior vary without changing the component that uses it?StrategyEncapsulate interchangeable behaviors behind a common contract.
How can object creation be separated from object usage?Factory Method or another factory approachCentralize or delegate construction decisions.
How can a component notify multiple interested consumers?ObserverRepresent a relationship between a publisher and subscribers.
How can new behavior be added without modifying the original implementation?DecoratorCompose behavior around an existing object.
How can two incompatible interfaces work together?AdapterTranslate one interface into another.
How can behavior vary according to the current state?StateRepresent state-specific behavior and transitions explicitly.

These are starting points, not automatic rules.

For example, a Factory is not always necessary just because an application creates objects. A direct constructor call is often the clearest choice.

Similarly, Strategy is not automatically better than a conditional expression. It becomes valuable when interchangeable behaviors need independent implementations or lifecycle management.

The purpose of learning patterns is to recognize these design options and understand their consequences.

3.1 A pattern is a design choice, not a framework requirement

Suppose an application needs to send email notifications.

You could implement a notification interface, create several classes, introduce a factory, and register each implementation in a dependency injection container.

You could also write a single function that sends an email through a provider.

Both can be reasonable designs.

The first becomes attractive when notification delivery has multiple implementations, independent configuration, or changing requirements. The second may be better when the application has one stable provider and little additional complexity.

A pattern should be introduced because its structure helps solve an existing or sufficiently likely problem—not because a design guide says it is a recognized pattern.

4. A Practical Example: From Conditional Logic to Strategy

Let's return to the payment example and work through a possible refactoring.

The goal is not to eliminate every conditional statement. It is to separate payment behavior so that the order processing code does not need to know how each provider works.

4.1 Step one: Define the behavior the application needs

Start with a small contract:

typescript
interface PaymentGateway {
  charge(
    orderId: string,
    amount: number,
  ): Promise<void>;
}

This contract represents the capability the application requires.

It does not expose provider-specific methods such as createPayment, transfer, or captureCharge.

That distinction matters because the application can now depend on a consistent operation.

4.2 Step two: Implement the contract for each provider

typescript
class StripeGateway implements PaymentGateway {
  async charge(
    orderId: string,
    amount: number,
  ): Promise<void> {
    await stripeClient.charge({
      orderId,
      amount,
    });
  }
}

class PayPalGateway implements PaymentGateway {
  async charge(
    orderId: string,
    amount: number,
  ): Promise<void> {
    await paypalClient.createPayment({
      orderId,
      amount,
    });
  }
}

Each implementation translates the common application operation into the provider's specific API.

In a production system, these adapters would also need to handle provider-specific errors, idempotency, response validation, and payment lifecycle differences. Those details are omitted here to keep the design example focused.

4.3 Step three: Make the payment operation independent of the provider

typescript
class OrderPaymentService {
  constructor(
    private readonly gateway: PaymentGateway,
  ) {}

  async pay(
    orderId: string,
    amount: number,
  ): Promise<void> {
    await this.gateway.charge(
      orderId,
      amount,
    );
  }
}

The service no longer decides how Stripe or PayPal processes a payment.

It uses the behavior exposed by the PaymentGateway contract.

The concrete gateway can be provided when the service is constructed:

typescript
const gateway = new StripeGateway();

const paymentService = new OrderPaymentService(
  gateway,
);

await paymentService.pay("order-123", 100);

The example uses direct construction for clarity. A larger application might use a composition root or dependency injection container to manage these dependencies.

4.4 What actually improved?

The benefit is not simply that we introduced an interface.

The design now separates two different responsibilities:

  • OrderPaymentService coordinates the application's payment operation.
  • Each gateway handles communication with a specific payment provider.

This can improve testing, because the payment service can receive a fake gateway. It can also make provider implementations easier to replace or extend.

However, one important decision remains: how does the application select the correct gateway?

If a user can select a payment method at runtime, the system still needs a mapping from that choice to a gateway implementation. That selection may be handled by a factory, registry, or application service, depending on the requirements.

Strategy does not automatically solve object creation, provider registration, or payment orchestration. It addresses the separation of interchangeable behavior.

4.5 Did we really need Strategy?

Not necessarily.

If the application will always use one provider and there is no meaningful variation in payment behavior, the original implementation may be simpler and easier to maintain.

If provider-specific logic is growing, several implementations are required, and the system needs to isolate provider changes, the abstraction becomes more valuable.

This is the central lesson:

The quality of a pattern-based design depends on whether its additional structure solves a real problem.

The Strategy Pattern is useful because it gives interchangeable behaviors a clear boundary—not because every if/else statement should be replaced by an interface.

5. The Trade-Off: Every Abstraction Has a Cost

Design patterns can improve maintainability, but they are not free.

Every abstraction introduces another concept that developers must understand, navigate, test, and maintain.

5.1 More code does not automatically mean better design

Compare a small conditional function with a design that includes:

  • A behavior interface.
  • Several implementation classes.
  • A factory.
  • A registry.
  • A dependency injection configuration.
  • A set of additional tests.

This structure may be justified in a system with many interchangeable implementations. It may be excessive for a simple, stable operation.

The right level of abstraction depends on the complexity and expected evolution of the system.

5.2 Abstractions can hide important behavior

An abstraction is useful when it hides irrelevant implementation details while preserving the behavior callers need to understand.

It becomes harmful when it conceals important differences.

For example, two payment providers may both implement charge, but one may complete synchronously while the other returns a pending transaction that requires a webhook confirmation.

Forcing both into an overly simplistic contract can hide meaningful differences in their lifecycles.

A good abstraction does not pretend that implementations are identical. It defines a common contract while making important variations explicit.

5.3 Patterns can move complexity instead of removing it

Introducing a Factory may remove construction logic from a service, but the Factory must now decide which implementation to create.

Introducing an Observer may reduce direct dependencies between components, but the system must now manage subscription lifecycles, event ordering, error handling, and potentially asynchronous delivery.

Introducing a Decorator may isolate cross-cutting behavior, but debugging a deeply nested chain of decorators can become difficult.

These are not arguments against the patterns. They are reminders that complexity has to be managed somewhere.

A useful design makes that complexity explicit and puts it in a place where it can be understood and controlled.

5.4 Avoid designing for every possible future

It is tempting to add abstractions because a requirement might change someday.

But hypothetical flexibility has a cost today.

A more practical approach is to identify the dimensions of change that are already visible in the requirements, then design a boundary around them when the benefit justifies the cost.

You do not need to predict every future feature. You need to avoid making likely changes unnecessarily expensive.

6. How to Recognize When a Pattern Is Needed

There is no universal metric that tells you when to introduce a design pattern. However, several recurring signs can help guide the decision.

6.1 The same decision is repeated across the codebase

If multiple modules independently decide which payment provider, notification channel, or pricing rule to use, the selection logic may need a single, well-defined owner.

Depending on the problem, a factory, registry, or application service may help.

6.2 Adding a new behavior requires modifying unrelated components

If every new implementation requires changes to multiple parts of the system, consider whether those components depend too directly on concrete implementations.

Strategy, Adapter, and other patterns can help isolate changes, but the correct choice depends on what is varying and why.

6.3 One component owns too many different responsibilities

A service may handle API requests, validation, persistence, notification delivery, and external integration.

The problem is not necessarily its size. It is the number of independent reasons it may need to change.

Before introducing a pattern, identify which responsibilities should be separated. A simple function extraction or module boundary may be enough.

6.4 Testing requires too much unrelated setup

If testing one business decision requires launching a database, constructing an HTTP server, and connecting to a real external provider, the code may be too tightly coupled to its environment.

Dependency boundaries, interfaces, and suitable patterns can help isolate the behavior under test.

However, not every dependency needs an interface. A stable, deterministic utility may not need one.

6.5 You are solving the same structural problem repeatedly

Patterns become particularly useful when the same type of design problem appears across different features.

For example, if several integrations need to translate external APIs into a common internal contract, Adapter may provide a reusable way to structure those integrations.

The key is to recognize the recurring problem—not simply to reuse the same class structure everywhere.

A practical decision checklist

Before introducing a pattern, ask:

  1. What specific problem am I solving?
  2. Which responsibility or dependency is making the current design difficult to change?
  3. Is the variation real, or am I designing for a hypothetical requirement?
  4. Would a simpler function, module, or conditional expression be sufficient?
  5. What additional complexity will the pattern introduce?
  6. How will I know that the resulting design is better?

If you cannot clearly explain the problem, it is usually too early to introduce the pattern.

7. Common Misconceptions About Design Patterns

Misconception 1: More patterns mean better code

A codebase can use dozens of recognized patterns and still be difficult to maintain.

Patterns improve design only when their structures are appropriate for the problems being solved.

A small function with a clear purpose may be better than a class hierarchy designed to accommodate every possible variation.

Misconception 2: Every conditional should become polymorphism

Conditional logic is a normal part of programming.

A short if statement is often the clearest representation of a simple decision.

Polymorphism becomes useful when different implementations represent meaningful, independently changing behaviors. Replacing every conditional with a class adds indirection without necessarily improving the design.

Misconception 3: Design patterns are the same as architectural patterns

Design patterns and architectural patterns operate at different levels of abstraction, although their boundaries are not absolute.

Design patterns such as Strategy, Adapter, and Observer generally address more localized relationships between objects or components.

Architectural patterns such as Layered Architecture and MVC organize broader responsibilities and interactions across parts of an application.

A system can use both. For example, an application may follow Layered Architecture and use Strategy within its application or domain logic.

Misconception 4: Design patterns belong exclusively to OOP

Many classic design patterns are expressed using classes, interfaces, and object composition because they emerged from object-oriented design.

However, the underlying ideas are not limited to class-based languages.

A Strategy can be represented by a function. An Adapter can be a wrapper function or module. An Observer-like mechanism can be implemented through callbacks or event streams.

The implementation should fit the language and programming model rather than reproduce a class diagram mechanically.

Misconception 5: A pattern guarantees compliance with SOLID

Patterns can support principles such as the Open/Closed Principle, Single Responsibility Principle, and Dependency Inversion Principle.

But they do not guarantee those principles are satisfied.

A poorly designed Strategy hierarchy can violate responsibility boundaries. A Factory can depend on concrete classes throughout the application. An Observer implementation can create hidden coupling through shared global state.

Patterns are tools for expressing design decisions. The quality of those decisions still matters.

Misconception 6: If a pattern is widely used, it must be appropriate

A pattern may be effective in one context and unnecessary in another.

For example, Observer is useful when multiple consumers need to react to changes without being directly coupled to the producer. For a simple operation with one known caller, a direct function call may be clearer.

Context determines whether the benefits justify the additional structure.

8. Design Patterns in Real Applications

In production systems, patterns rarely exist in isolation. They often work together to address different parts of a workflow.

Consider a backend application that processes an order.

A possible design might use:

  • Strategy to select among pricing or payment behaviors.
  • Adapter to translate a payment provider's API into an internal contract.
  • Factory to create or select an appropriate implementation.
  • Decorator to add logging or caching around a service where suitable.
  • Observer to notify independent consumers when an order event occurs.
  • State to model meaningful order lifecycle transitions.

These patterns address different problems. They should not all be introduced simply because the system processes orders.

For example, payment provider integration may justify an Adapter because the external API differs from the application's internal contract. Strategy may also be appropriate if the application supports several interchangeable payment implementations.

But a Factory is only needed if object creation or implementation selection requires separate coordination. An Observer is only useful if the event relationships justify the additional complexity.

The design should emerge from the actual requirements.

8.1 Patterns complement broader architecture

Suppose the application uses Layered Architecture:

  • The Presentation Layer receives requests.
  • The Application Layer coordinates use cases.
  • The Domain Layer represents business rules.
  • The Infrastructure Layer integrates with databases and external providers.

Design patterns can help organize behavior within those boundaries.

An Adapter might live in the Infrastructure Layer. A Strategy might represent alternative domain policies. A Factory might be used to construct an appropriate implementation.

The exact placement depends on the responsibilities and dependency rules of the application.

A pattern does not replace architectural boundaries. Nor does using a pattern automatically produce a clean architecture.

8.2 Patterns should make dependencies more intentional

A useful pattern-based design makes it clearer which component knows about which other component.

For example, an application service that depends on a payment contract does not need to know the details of the provider's HTTP API.

An Adapter translates between those two worlds.

This boundary can make it easier to test application behavior independently and to isolate changes in external integrations.

However, the application still needs to define how the adapter is constructed, how failures are handled, and what guarantees the payment contract provides.

A design pattern addresses part of the problem. The surrounding architecture must complete the picture.

9. A Practical Approach to Learning Design Patterns

Memorizing pattern names is useful only up to a point. To become effective at applying them, practice reasoning from problems to design decisions.

Step 1: Start with a concrete problem

Take a real feature from an application you have worked on.

Look for repeated conditions, growing classes, duplicated decisions, or dependencies that make testing difficult.

Do not start by selecting a pattern.

Step 2: Write down the current responsibilities

Identify what the code is responsible for and which parts change independently.

Ask whether one component is making too many decisions or depending on implementation details it does not need to know.

Step 3: Explore the simplest solution first

Could a function extraction solve the problem? Would moving a decision into one module be enough? Is a small interface sufficient?

Not every design problem needs a recognized pattern.

Step 4: Identify the relevant pattern

Once the problem is clear, investigate the patterns that address it.

Compare their underlying ideas rather than focusing only on their class diagrams.

For example, Strategy and State can both use composition and polymorphism, but they address different questions: interchangeable behavior versus behavior that depends on the current state.

Step 5: Compare the designs

Implement the simpler design and the pattern-based alternative.

Compare them in terms of:

  • How easily a new requirement can be added.
  • How much existing code needs to change.
  • How clearly responsibilities are expressed.
  • How easily the behavior can be tested.
  • How much additional code and indirection are introduced.

The best choice is the one that provides meaningful benefits for the system's actual needs.

Step 6: Learn when not to use the pattern

This step is just as important as learning the implementation.

For each pattern, understand the conditions that make it useful, its limitations, and the simpler alternatives that may be more appropriate.

Being able to reject a pattern for good reasons is a sign of design maturity, not a lack of knowledge.


Summary

Design patterns provide reusable ways to reason about recurring software design problems. They help developers organize responsibilities, control dependencies, and manage changes that would otherwise make a system increasingly difficult to maintain.

But patterns are not universal solutions.

An interface does not automatically make code flexible. A Factory does not automatically simplify object creation. A Strategy does not automatically improve every conditional. The value of an abstraction depends on the problem it addresses and the complexity it introduces.

A practical approach to design patterns begins with the code and the requirements:

  • Identify the source of complexity.
  • Determine which responsibilities or dependencies should be separated.
  • Choose the simplest design that addresses the problem.
  • Introduce a pattern when its structure provides meaningful benefits.
  • Evaluate the resulting design against its trade-offs.

The goal is not to use as many patterns as possible. It is to build software whose responsibilities are clear, whose dependencies are intentional, and whose behavior can evolve without unnecessary disruption.

Learn the problem before the pattern. Understand the trade-off before the abstraction. And remember that sometimes the best design is the one that needs no pattern at all.

  • Design Patterns
  • Programing
  • OOP
  • Architecture
  • Software Architecture
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading
Design Patterns · 19 min read

When Design Patterns Become Anti-Patterns

Design patterns solve recurring software design problems, but applying them without a clear purpose can introduce unnecessary complexity. Learn how to recognize overengineering, evaluate abstractions, and choose designs that make software easier to understand, test, and change.

Design Patterns · 17 min read

Unit of Work: Coordinating Data Changes

The Unit of Work Pattern helps coordinate multiple persistence operations as one business transaction. Explore a practical TypeScript example, learn how it works with repositories, and understand the limits of rollback, transaction boundaries, retries, and distributed systems.

Design Patterns · 17 min read

Repository Pattern: Abstraction or Unnecessary Layer?

The Repository Pattern can separate application logic from persistence, but it can also become an unnecessary wrapper around an ORM. Learn how to design meaningful repository contracts in TypeScript, test them effectively, and decide when direct database access is the simpler choice.