Every codebase eventually has a line like new StripeGateway(key) buried in business logic, and the day the company adds a second payment provider that line shows up in forty places. Creational design patterns exist for exactly that moment: they put the decision about which object to build and how in one place instead of scattering it. This guide covers the three that matter most in day-to-day work, Factory, Builder and Singleton, with code, and explains why the third one has a bad reputation.

Key takeaways

  • Creational patterns separate using an object from deciding how to construct it, so a new variant means one new class, not forty edits.
  • Use a Factory when the caller should not know which concrete class it gets; use a Builder when construction has many optional parts.
  • The 1994 Gang of Four book lists five creational patterns: Abstract Factory, Builder, Factory Method, Prototype and Singleton.
  • Singleton hides global state and makes tests harder; passing one shared instance in explicitly gives you the same benefit without the cost.
  • If a constructor with four arguments is readable, you do not need a pattern yet.
Working definition

A creational design pattern is a reusable way of creating objects that keeps the calling code independent of the concrete classes being instantiated.

The problem: construction leaks everywhere

In part 1 of this series we used Dependency Inversion to make code depend on behaviour instead of a vendor. That leaves one question open: somebody still has to write new somewhere. If every service does it for itself, the vendor name is back in the code, just one level lower.

// Everywhere in the codebase
const gateway = new StripeGateway(process.env.STRIPE_KEY);
await gateway.charge(order.total);

The same thing happens with objects that are simply awkward to build: a report with fourteen optional settings, an HTTP request with headers, retries and a timeout. The caller ends up knowing too much about how the thing is assembled. The Gang of Four book, Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson and Vlissides, first published in 1994), grouped the answers under the name creational patterns and listed five of them.

Diagram of the five creational patterns from the Gang of Four book with the question each one answers
Figure 1 — The five creational patterns in the 1994 book, each reduced to the question it answers. Diagram: AIGS, December 2026, based on the pattern list on Wikipedia’s Design Patterns article.

Factory: hide which class you get

A factory is a function or method that returns an object and decides, on the caller’s behalf, which concrete class to build. The caller asks for “a payment gateway” and receives something that honours the interface.

interface PaymentGateway { charge(amount: number): Promise<Receipt>; }

function createGateway(config: Config): PaymentGateway {
  switch (config.provider) {
    case 'stripe': return new StripeGateway(config.key);
    case 'paypal': return new PayPalGateway(config.clientId, config.secret);
    default: throw new Error('Unknown provider: ' + config.provider);
  }
}

// Callers never see a vendor name
const gateway = createGateway(config);

Adding a third provider now touches the factory and one new class. Every caller is unchanged. That is the whole pattern. The GoF book distinguishes Factory Method (a method that subclasses override to choose what to build) from Abstract Factory (an object that builds a whole family of related products, such as a UI toolkit’s buttons and dialogs for one operating system). In modern code a plain function like the one above covers most needs, and it is fine to call it a factory.

Tip

Keep the switch in exactly one place, close to where configuration is read. If the same switch appears in two files, the factory has leaked.

Builder: tame the many-argument constructor

Some objects have a few required values and many optional ones. A constructor with eleven positional arguments is unreadable, and every call site is a chance to swap two booleans. A builder collects the settings step by step and creates the object at the end.

const request = new RequestBuilder('https://api.example.com/orders')
  .method('POST')
  .header('Authorization', 'Bearer ' + token)
  .json({ sku: 'A-100', qty: 2 })
  .timeout(5000)
  .retries(3)
  .build();   // validates, then returns an immutable Request

Two details make a builder worth the extra class. First, build() is the one place that validates the combination, so an invalid object can never exist. Second, the built object can be immutable even though the builder is not. If your language has named arguments or object literals with defaults, you may not need a builder at all; many JavaScript and Python codebases pass a single options object instead and get most of the benefit.

Diagram comparing a Factory that returns one of several gateways and a Builder that assembles a request in steps
Figure 2 — Factory chooses which object; Builder controls how one object is assembled. Diagram: AIGS, December 2026.
A creational pattern earns its place when it removes a decision from forty call sites and puts it in one.

Singleton and the trap inside it

Singleton guarantees that a class has exactly one instance and gives everyone global access to it. It is the most famous pattern in the book and the most criticised. Wikipedia’s article records the objection plainly: some consider it an anti-pattern because it introduces global state, creates hidden dependencies between objects, and makes unit testing harder. Erich Gamma himself said in a 2009 interview that the authors would have liked to remove it from the book when they discussed a revision in 2005, but there was no consensus.

// The trap: any code can reach this, and tests cannot replace it
class Config {
  private static instance: Config;
  static get(): Config { return this.instance ??= new Config(); }
}
function price(order) { return order.total * (1 + Config.get().taxRate); }

price() looks pure, but it depends on a global that nothing in its signature admits. A test has to reset hidden state between runs, and two tests running in parallel can fight over it. The fix keeps the useful part, one shared instance, and drops the global access:

function makePricer(config: Config) {
  return (order) => order.total * (1 + config.taxRate);
}
// One Config is created at startup and passed in. Tests pass a fake.
const price = makePricer(loadConfig());

This is Dependency Inversion again. The application creates the single instance once, at its edge, and hands it to whoever needs it. You still have one object, but the dependency is visible and replaceable.

Diagram contrasting code that reaches a global singleton with code that receives one shared instance as a parameter
Figure 3 — Same single instance, different coupling. Diagram: AIGS, December 2026.

“Singleton is the right way to share a database connection.”

Sharing one connection pool is fine. Making it reachable from anywhere through a static method is the part that hurts tests. Create it once and pass it in.

“Every new keyword should be replaced by a factory.”

Building a value object or a plain data structure directly is fine. Use a factory where the concrete class is a decision that might change.

Choosing between them

  • The caller should not know the concrete class: Factory.
  • Many optional settings, or a need to validate the combination: Builder, or an options object if your language makes that easy.
  • Exactly one shared instance: create it once at startup and inject it; avoid static global access.
  • Copying an existing configured object: Prototype, the least used of the five, usually just a clone method.

The honest rule is the same as in the SOLID article: apply a pattern when you can point at the change it makes cheap. If you cannot name the second provider, the second format or the second environment, a plain constructor is still the right design.

A checklist you can run today

  • Search the codebase for new followed by a vendor or driver name inside business logic. Each hit is a candidate for a factory.
  • Find the constructor with the most parameters. If call sites pass several booleans or nulls, introduce a builder or an options object.
  • Search for getInstance, .instance or module-level state. For each, ask whether a test could replace it.
  • Check that every factory has one switch, in one file.
  • Write one test that builds the object with a fake dependency. If that is hard, the construction is still too tied to the real thing.

If a codebase has grown past the point where these fixes are quick, the AIGS systems analysis service starts with this kind of dependency map. For payloads and configuration you build with these patterns, our JSON formatter and validator is a quick way to check the output.

Screenshot of the AIGS JSON formatter and validator tool
Figure 4 — Our own JSON formatter and validator, handy for checking the configuration and request bodies your factories and builders produce. Screenshot: ai-gs.net, December 2026.
Further reading

The pattern list and the 1994 publication details are on Wikipedia’s Design Patterns article. The criticism of Singleton, including the link to dependency injection, is summarised in its Singleton pattern article.

Part 2 of 14 — Engineering Foundations series

Previous: SOLID Principles in Practice: Five Rules, Real Refactors. Next: structural design patterns, Adapter, Decorator and Facade, which deal with how objects fit together once they exist.

Browse the rest of the series on the AIGS blog, or see how we apply it in client work on the services page.