Skip to content

Creational Patterns: Singleton, Simple Factory, Factory Method, Abstract Factory, Builder, Prototype ​

"The important issue in all of this is to ensure that the configuration of services is separated from their use." — Martin Fowler, Inversion of Control Containers and the Dependency Injection pattern, 2004

Summary: Creational patterns decide who calls new, when, and which concrete class it gets. Today most of that job is done by plain constructors plus dependency injection at a composition root; the six patterns on this page are the tools you still reach for when creation itself has logic. Focus: Singleton (and why global singletons hurt tests), Simple Factory, Factory Method, Abstract Factory, Builder (including Go functional options), Prototype (shallow vs deep copy), plus static factory methods, lazy initialization, object pools, registries, DI containers vs the service-locator anti-pattern, test data builders, and how creation moves to configuration in microservices. Learning goal: Given a piece of code full of new/&T{} and if chains, name the creational problem, pick the smallest pattern that solves it (often just a constructor and injection), implement it idiomatically in Go and Laravel 13, and test it without globals.

This is the complete reference for the creational family of the Gang of Four catalogue, plus the Simple Factory that Head First made popular and the modern tools that replaced half of it. The map of all three families and the history of the GoF book live in Design Patterns: introduction; wrapping and composing objects is on Structural Patterns; behaviour and algorithms (Strategy, Template Method, Observer) are on Behavioral Patterns; combining patterns and spotting pattern abuse is on Patterns in practice. Two SOLID pages are the reason most creational code exists: Dependency Inversion (depend on interfaces, wire concretes at the edge) and Open–Closed (add a new product without editing callers).

Page map ​

If you are looking forGo to
All six patterns in two tablesEverything in one minute
Why creation needs patterns at allWhy creational patterns exist
GoF 1994, Head First, Pike and Cheney, Fowler, SeemannWhere it comes from
Singleton, thread safety, sync.Once, Laravel singleton/scopedSingleton
One function with a switch/matchSimple Factory
Subclass or hook decides the productFactory Method
A family of products that must matchAbstract Factory
Step-by-step construction, functional options, fluent buildersBuilder
Copying a configured object, clone, __clone, deep copyPrototype
Named constructors, lazy init, pools, registries, DI, service locator, Object MotherSupporting concepts
How Go, Laravel, Spring, .NET, TypeScript and Python create objectsPer-language view
Container lifetimes, thread-safety rules, error messagesMechanics
Before/after codeGo, Laravel
Telescoping constructors, scattered new, global config, test dataSolving the classic problems
Which pattern for which situationChoosing
Monolith → microservices → distributedIn architecture
Hands-on notification system with testsLab
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The six patterns. Every row is unpacked in its own block below.

PatternIn plain wordsTiny exampleGo idiomLaravel idiom
SingletonExactly one instance, reachable from anywhereOne config object, one loggerBuild once in main and pass it; sync.OnceValue if it must be lazy$this->app->singleton(), #[Singleton], scoped() per request
Simple FactoryOne function picks the class with a switchNewChannel("sms")func New(kind string) (Channel, error)match in a factory class or a backed enum make()
Factory MethodThe algorithm is fixed; a hook decides which productNotifier::notify() calls createChannel()Creator holds an interface or func() TAbstract method overridden by a subclass
Abstract FactoryOne object creates a whole matching familyIranKit makes SMS + mail + formatterInterface with several NewX() methodsInterface bound in a service provider; contextual binding per consumer
BuilderAssemble a complex object step by step, validate onceSmsMessageBuilder::create()->to()->line()->build()Functional options; step builder with Build() (T, error)Query builder, Http::withToken()->retry(), MailMessage, model factories
PrototypeCopy a configured object instead of rebuilding itClone a receipt template per tenantClone() with maps.Clone/slices.Cloneclone + __clone(), $model->replicate()

Which problem, which tool.

You have this problemSmallest fixPattern name, if you need one
A class needs a collaboratorConstructor parameterDependency injection
Business code says new SmtpMailerInject an interface, build it at the composition rootDI + factory at the root
The class to build depends on input ("sms", "mail")One function with a switchSimple Factory
A reusable algorithm must stay closed while products varyHook method or function fieldFactory Method
Several products must always come from the same familyOne interface that creates them allAbstract Factory
Ten optional parameters, invariants to checkOptions or a builder with Build()Builder
Building is expensive, copies differ slightlyCopy, then tweakPrototype
Exactly one per processCreate once in main / container singletonSingleton (lifetime, not a static)
Expensive object, maybe never usedCreate on first useLazy initialization
Many short-lived, costly allocationsReuse instancesObject pool

Lifetimes you will meet.

LifetimeLaravel 13Go.NETSpring
New every time (transient)bind() (default for auto-resolved classes)Call the constructorAddTransientprototype scope
One per request / jobscoped(), #[Scoped]Create in the handler, pass down; context for request valuesAddScopedrequest scope
One per processsingleton(), #[Singleton], instance()Create in main; package var with sync.OnceValueAddSingletonsingleton scope (the default)

Why creational patterns exist ​

Every new is a decision: this class, now, with these arguments. When that decision sits inside business code, three things go wrong at once. The code is welded to one concrete class (you cannot send SMS through a different gateway without editing the order service). The code needs to know how to build its collaborators (credentials, URLs, timeouts leak into places that should only care about "send a message"). And tests have to build the real thing (a real SMTP connection) or patch globals. Creational patterns move the decision somewhere else: into a function, a subclass, a family object, a builder, a copy, or, in modern code, into the composition root.

Creation inside business codeCreation moved out
Simple to read on day oneOne more indirection to follow
Each caller repeats the same if on configurationOne place decides
Swapping an implementation edits many filesSwapping edits one binding or one factory
Tests need real infrastructure or global patchesTests inject fakes through constructors
Hidden dependencies (Settings::instance() deep inside)Dependencies visible in signatures
Risk: rigid, untestableRisk: factories for things that never vary (over-engineering)

The analogy we reuse on this page: a post office. There is one postmaster for the branch (Singleton, but the city appoints him; he does not appoint himself). The counter clerk looks at your parcel and picks the form: letter, parcel, registered (Simple Factory). Each branch follows the same procedure but decides which courier carries it (Factory Method). A domestic kit and an international kit each contain matching forms, stamps and envelopes; you never mix an international stamp with a domestic form (Abstract Factory). A registered parcel is assembled step by step: address, insurance, tracking, signature, and the clerk checks it once before accepting it (Builder). For a mass mailing you photocopy a filled template and change the name (Prototype).

Three common misunderstandings, up front ​

  1. "Use a factory everywhere instead of new." A factory earns its place only when creation has logic (a choice, a family, invariants, cost). A constructor plus injection is the default; a factory for a class with one implementation is ceremony.
  2. "Singleton means one instance, so it is fine for anything I only need once." "Only one" is a lifetime decision that belongs to the composition root. The GoF Singleton adds a second thing, global access, and that is what hurts tests and hides coupling.
  3. "Factory Method is any method that returns a new object." That is a static factory method (a named constructor, like Money::of() or time.Now()). The GoF Factory Method is a hook in a class hierarchy (or, in Go, an interface or function value) that lets a fixed algorithm defer the choice of product.
Composition root (main / ServiceProvider)config + feature flags → factories → objectsHTTP handlerqueue consumerNotifyServiceKit / Repositorydependencies visible in constructorswrong wiring fails at startup or in one testService locator (anti-pattern)global container / registryOrderServiceInvoiceJobapp(X::class) inside methods:dependencies hidden, fail at run time,tests must configure the globalinjectspullspulls

The picture is the end state this page argues for: factories and builders still exist, but they are called from one place, the composition root, and everything below it receives interfaces. The right half is what to avoid: classes that pull their dependencies from a global container.

Where it comes from ​

Gamma, Helm, Johnson, Vlissides, 1994. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley) groups 23 patterns into creational, structural and behavioral. Its creational chapter has five: Abstract Factory, Builder, Factory Method, Prototype and Singleton. We did not have the book text in hand; the intent statements below are as quoted, with page references, on Wikipedia (a secondary source):

PatternGoF intent (as quoted on Wikipedia)
Factory Method"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses."
Abstract Factory"Provide an interface for creating families of related or dependent objects without specifying their concrete classes."
Builder"separate the construction of a complex object from its representation", so that "the same construction process can create different representations" (paraphrased by Wikipedia from GoF p. 97)

The same Wikipedia article on Prototype summarises the book's comparison: "designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward abstract factory, prototype, or builder (more flexible, more complex) as the designer discovers where more flexibility is needed."

Freeman and Robson, Head First Design Patterns, 2004. Refactoring.guru credits this book with the Simple Factory: "a class that has one creation method with a large conditional that based on method parameters chooses which product class to instantiate and then return." It is not one of the 23, and refactoring.guru adds a warning worth memorising: "if you declare a simple factory abstract, it doesn't magically become the abstract factory pattern."

Fowler, 2004. Inversion of Control Containers and the Dependency Injection pattern named Dependency Injection, contrasted it with Service Locator, and gave the rule quoted at the top: configuration of services separated from their use. That article is why most application code today does not call factories directly; a container or main does.

Seemann, 2010. Service Locator is an Anti-Pattern argued that a locator "hides a class' dependencies, causing run-time errors instead of compile-time errors". His later term Composition Root (the single place where the object graph is composed) is the vocabulary this page uses.

Pike and Cheney, 2014. Rob Pike's Self-referential functions and the design of options (January 2014) introduced the option-as-function idea: "First, we define an option type. It is a function that takes one argument, the Foo we are operating on." Dave Cheney's talk Functional options for friendly APIs (October 2014) turned it into the Go idiom for configurable constructors, an API with "sensible defaults", that "is highly configurable", "can grow over time" and is "self documenting". It is Go's Builder.

Recent language features that changed creational code.

YearFeatureEffect on creation
2023Go 1.21 sync.OnceFunc, sync.OnceValue, sync.OnceValuesLazy, thread-safe singletons in one line
2024PHP 8.4 lazy objects (ReflectionClass::newLazyGhost(), newLazyProxy())Lazy initialization without hand-written proxies
2025PHP 8.5 clone($obj, [...]) with property overridesPrototype "withers" for readonly objects in one call
Laravel 13 docs#[Singleton], #[Scoped], #[Bind], #[BindWhen] container attributesThe class declares its lifetime; fewer provider lines
—Google Wire (Go compile-time DI) marked "no longer maintained" in its READMEHand-written composition roots are the Go default

The concepts, one by one ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, the structure diagram and participants, a timeline, real scenarios, Go and Laravel code, consequences, when not to use it, related patterns.

Singleton Important ​

In plain words: a class that guarantees there is only one of it and gives everyone a way to reach that one.

Common misunderstanding: "A singleton is how you share one database pool or logger." Sharing one instance is a lifetime decision, and main (or the container) can make it without the class knowing. The GoF version also bakes global access into the class, and that is the part that turns into hidden coupling and test pain.

Definition: refactoring.guru: "Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance." The same page lists the cost plainly: it "Violates the Single Responsibility Principle. The pattern solves two problems at the time", it "can mask bad design", and it "requires special treatment in a multithreaded environment so that multiple threads won't create a singleton object several times."

GoF Singleton (global access)Singleton- static instance: Singleton- __construct() private+ static getInstance(): Singletonlazy: create on first callClientAClientBTestevery client names the class: hidden couplingLifetime owned by the composition rootContainer / mainbind: new object every timescoped: one per request or jobsingleton: one per processGo: build once in main, pass pointerClientAClientBTest: fakeclients receive the instance; tests pass their owngetInstance()injectstest injects fake
ParticipantRoleGoLaravel
SingletonHolds the one instance, hides the constructorUnexported type + package var + sync.Onceprivate function __construct, static ?self $instance
getInstance()Lazy creation and global accessfunc Instance() *ConfigSettings::instance()
ClientUses itAny package that imports itAny class that calls it
Modern replacementOwns the lifetime insteadmain builds once, passes pointersingleton(), scoped(), #[Singleton]
text
     Step  Goroutine / request            Broken lazy singleton            sync.Once / OnceValue
1    t0    G1: Instance()                 sees nil, starts load()          enters once.Do, runs load()
2    t0    G2: Instance()                 also sees nil, starts load()     blocks until G1's load() returns
3    t1    G1                             assigns instance A                returns A
4    t1    G2                             overwrites with instance B        returns A (same pointer)
5    --    result                         two configs, a data race          one config, race-free

Real scenario: a process-wide slog.Logger; a *sql.DB (its docs say "The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once"); an HTTP client with tuned transport; exchange-rate cache; feature-flag client; in Laravel a stateless API client registered with singleton() and a per-tenant context registered with scoped().

Go: four versions from worst to best, and a test that proves sync.OnceValue runs the initializer once under 100 goroutines.

go
// Package singleton shows four ways to get "one instance" in Go,
// from the broken one to the one we recommend.
package singleton

import (
	"os"
	"sync"
)

// Config is expensive to build (reads env, files, secrets).
type Config struct {
	DSN      string
	SMSToken string
}

func load() *Config {
	return &Config{DSN: os.Getenv("DATABASE_URL"), SMSToken: os.Getenv("SMS_TOKEN")}
}

// 1. Broken: two goroutines can both see nil and both call load
// (a data race; `go test -race` reports it).
var racy *Config

func RacyInstance() *Config {
	if racy == nil {
		racy = load()
	}
	return racy
}

// 2. Classic GoF singleton, made thread-safe with sync.Once.
// The return from load "synchronizes before" every return from once.Do.
var (
	once     sync.Once
	instance *Config
)

func Instance() *Config {
	once.Do(func() { instance = load() })
	return instance
}

// 3. Go 1.21+: the same lazy, thread-safe initialization in one line.
var Shared = sync.OnceValue(load)

// 4. Recommended: "one instance" is a decision of main, not of the type.
// main calls load once and passes the pointer to everyone who needs it;
// tests pass their own Config without touching a global.
type Sender struct{ cfg *Config }

func NewSender(cfg *Config) *Sender { return &Sender{cfg: cfg} }

func (s *Sender) Token() string { return s.cfg.SMSToken }
go
package singleton

import (
	"sync"
	"sync/atomic"
	"testing"
)

func TestOnceValueRunsOnce(t *testing.T) {
	var calls atomic.Int32
	get := sync.OnceValue(func() *Config { calls.Add(1); return &Config{DSN: "x"} })
	var wg sync.WaitGroup
	for range 100 {
		wg.Add(1)
		go func() { defer wg.Done(); _ = get() }()
	}
	wg.Wait()
	if calls.Load() != 1 {
		t.Fatalf("initializer ran %d times", calls.Load())
	}
}

func TestInjectedConfigNeedsNoGlobal(t *testing.T) {
	s := NewSender(&Config{SMSToken: "test-token"})
	if s.Token() != "test-token" {
		t.Fatal("wrong token")
	}
}

Laravel: the classic static singleton, then the container way. Laravel 13's container docs: "The singleton method binds a class or interface into the container that should only be resolved one time", and "The scoped method binds a class or interface into the container that should only be resolved one time within a given Laravel request / job lifecycle", flushed "when a Laravel Octane worker processes a new request or when a Laravel queue worker processes a new job".

php
<?php

// 1. Classic GoF singleton: private constructor, static instance.
// Works, but every caller is hard-wired to it and tests cannot swap it.

namespace App\Legacy;

final class Settings
{
    private static ?self $instance = null;

    /** @param array<string, mixed> $values */
    private function __construct(private array $values) {}

    public static function instance(): self
    {
        // PHP-FPM: one instance per request (share-nothing).
        // Octane / queue worker: the same instance lives for many requests.
        return self::$instance ??= new self(require base_path('config/settings.php'));
    }

    public function get(string $key, mixed $default = null): mixed
    {
        return $this->values[$key] ?? $default;
    }

    private function __clone() {}

    public function __wakeup(): void
    {
        throw new \LogicException('Cannot unserialize a singleton.');
    }
}

// 2. Laravel way: the class is ordinary; the container decides "one instance".

namespace App\Providers;

use App\Services\ExchangeRates;
use App\Services\TenantContext;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // One per process: stateless, expensive to build, safe to share.
        $this->app->singleton(ExchangeRates::class, function (Application $app) {
            return new ExchangeRates(config('services.rates.url'), $app->make('cache.store'));
        });

        // One per request / job: holds per-request state (tenant, user).
        // Flushed when Octane starts a new request or a worker starts a new job.
        $this->app->scoped(TenantContext::class, fn () => new TenantContext());
    }
}

// 3. Attribute form (Laravel 13): the class declares its own lifetime.

namespace App\Services;

use Illuminate\Container\Attributes\Scoped;
use Illuminate\Container\Attributes\Singleton;

#[Singleton]
final class ExchangeRates
{
    public function __construct(private string $url, private \Illuminate\Contracts\Cache\Repository $cache) {}
}

#[Scoped]
final class TenantContext
{
    public ?int $tenantId = null;
}

Consequences: one instance guaranteed; lazy creation; but a global access point, hidden dependencies, order-of-initialization bugs, state that leaks between tests, and in long-running PHP (Octane, queue workers) state that leaks between requests.

When not to use it: when "one" is only true today (one database today, read replicas tomorrow); when the object holds per-user or per-request state; when you want to test callers in isolation; when the "singleton" is really configuration (pass a value instead).

Related: Abstract Factory, Builder and Prototype are often implemented as singletons (GoF, via Wikipedia); Object pool and Registry are its many-instance cousins; Multiton keeps one instance per key.

Simple Factory Must-know ​

In plain words: one function that looks at an input and decides which class to create, so the if lives in one place instead of twenty.

Common misunderstanding: "Simple Factory is the Factory Method pattern." It is not one of the GoF patterns at all. It has no hook and no subclassing; it is a parameterized function with a conditional. Refactoring.guru calls it "an intermediate step of introducing Factory Method or Abstract Factory patterns".

Definition: a creation function (or a class with one creation method) that takes a discriminator (a string, an enum, a config value), returns an interface, and is the only code that names the concrete classes. Adding a new product edits the factory, which is a deliberate, local violation of OCP in exchange for simplicity.

ClientChannelFactory+ make(kind): Channelmatch kind: mail | sms | push | error«interface»ChannelMailChannelSmsChannelPushChannelOne method, one conditional. New kind = edit the match (not OCP), but only here.make("sms")usescreatesimplements
ParticipantRoleExample
ClientAsks for a product by kindOrderShippedListener
FactoryHolds the switch/matchChannelFactory::make(), simplefactory.New()
Product interfaceWhat the client usesChannel
Concrete productsWhat the factory buildsMailChannel, SmsChannel, PushChannel
text
     Day   Change                                    Without a factory                 With a simple factory
1    D1    add "push" channel                        edit 7 call sites with if/else    edit 1 match, add 1 class
2    D1    -- a call site is missed; push users get email --
3    D9    config typo "smss"                        silent fallback to mail           error: unknown channel "smss"
4    D20   tests need a fake                         patch 7 places                    factory or binding returns the fake

Real scenario: Laravel's own Illuminate\Database\Connectors\ConnectionFactory is a simple factory: createConnector() does match ($config['driver']) over 'mysql', 'mariadb', 'pgsql', 'sqlite', 'sqlsrv' and returns the matching connector, and createConnection() does the same for connection classes. Other real ones: a payment-gateway factory keyed by country; a parser factory keyed by file extension; an exporter factory keyed by ?format=csv|xlsx.

Go: return an interface and an error for unknown kinds; never panic on user input.

go
// Package simplefactory: one function, one switch, returns an interface.
package simplefactory

import (
	"context"
	"errors"
	"fmt"
)

// Channel is the product interface every caller depends on.
type Channel interface {
	Send(ctx context.Context, to, body string) error
}

type Email struct{ From string }
type SMS struct{ SenderID string }
type Push struct{ AppID string }

func (e *Email) Send(ctx context.Context, to, body string) error { return nil }
func (s *SMS) Send(ctx context.Context, to, body string) error   { return nil }
func (p *Push) Send(ctx context.Context, to, body string) error  { return nil }

// Config is what the factory needs to build any channel.
type Config struct {
	MailFrom string
	SMSID    string
	PushApp  string
}

var ErrUnknownChannel = errors.New("unknown channel")

// New is the simple factory: the only place that knows the concrete types.
// Adding a channel means editing this switch (the OCP cost of the pattern).
func New(kind string, cfg Config) (Channel, error) {
	switch kind {
	case "email":
		return &Email{From: cfg.MailFrom}, nil
	case "sms":
		return &SMS{SenderID: cfg.SMSID}, nil
	case "push":
		return &Push{AppID: cfg.PushApp}, nil
	default:
		return nil, fmt.Errorf("%w: %q", ErrUnknownChannel, kind)
	}
}

Laravel: the same as a class, and as a backed enum whose make() method is the factory and whose tryFrom() validates input at the edge. PHP's manual: static methods on enums are "primarily for alternative constructors".

php
<?php

namespace App\Notifications\Channels;

use InvalidArgumentException;

interface Channel
{
    public function send(string $to, string $text): void;
}

final class MailChannel implements Channel
{
    public function __construct(private string $from) {}

    public function send(string $to, string $text): void { /* Mail::raw(...) */ }
}

final class SmsChannel implements Channel
{
    public function __construct(private string $senderId) {}

    public function send(string $to, string $text): void { /* HTTP call to the gateway */ }
}

// Simple factory as a backed enum: the list of kinds and the creation rule
// live together, and tryFrom() rejects unknown input at the edge.
enum ChannelKind: string
{
    case Mail = 'mail';
    case Sms = 'sms';

    public function make(): Channel
    {
        return match ($this) {
            self::Mail => new MailChannel(config('mail.from.address')),
            self::Sms => new SmsChannel(config('services.sms.sender_id')),
        };
    }

    // Static factory method ("named constructor") on the enum.
    public static function fromUserPreference(bool $prefersSms): self
    {
        return $prefersSms ? self::Sms : self::Mail;
    }
}

// The same thing as a plain class, the shape Laravel's own
// Illuminate\Database\Connectors\ConnectionFactory uses (match on 'driver').
final class ChannelFactory
{
    public function make(string $kind): Channel
    {
        return match ($kind) {
            'mail' => new MailChannel(config('mail.from.address')),
            'sms' => new SmsChannel(config('services.sms.sender_id')),
            default => throw new InvalidArgumentException("Unsupported channel [{$kind}]."),
        };
    }
}

Consequences: one place knows the concrete classes; unknown input fails loudly; but the conditional grows and every new product edits it.

When not to use it: when there is only one product; when plugins from other packages must add products without editing your code (use a registry or the Laravel Manager::extend() hook); when the switch keeps growing extra parameters per branch (move to Factory Method or Abstract Factory).

Related: grows into Factory Method (move branches to subclasses/hooks) or Abstract Factory (branches become families); the registry variant replaces the switch with a map.

Factory Method Must-know ​

In plain words: a class runs a fixed procedure and, at one step, asks a hook "which object should I use here?". Subclasses (or, in Go, the value you plug in) answer.

Common misunderstanding: "User::create() or NewServer() is the Factory Method pattern." Those are static factory methods (named constructors). The GoF pattern is about deferring the choice to a subclass or plug-in while the creator's algorithm stays the same. It is the creational twin of Template Method.

Definition: refactoring.guru: "Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created." GoF (via Wikipedia): "let subclasses decide which class to instantiate".

Creator: abstract Notifier+ notify(to, text) (the algorithm) ch = createChannel(); ch.send(...)# createChannel(): Channel (factory method)MailNotifiercreateChannel()SmsNotifiercreateChannel()«interface» ProductChannel.send()MailChannelSmsChannelSubclasses decide which class to instantiate; the creator's algorithm never changes.Go: Notifier holds a ChannelCreator interface or a func() Channel instead of a subclass.usescreatescreatesextends
ParticipantRolePHPGo
ProductInterface of what is createdChannelChannel
Concrete productReal implementationMailChannel, SmsChannelemail, sms
CreatorHolds the algorithm, declares the factory methodabstract class Notifier with createChannel()Notifier holding a ChannelCreator
Concrete creatorOverrides the factory methodMailNotifier, SmsNotifierEmailCreator, SMSCreator, ChannelFunc
text
     Step  Notifier::notify($to, $text)          MailNotifier                 SmsNotifier
1          validate recipient (shared)
2          $ch = $this->createChannel()  ------> new MailChannel(...)         new SmsChannel(...)
3          $text = $this->decorate($text)        unchanged                    cut to 160 chars
4          $ch->send($to, $text)
5          -- the algorithm (1..4) never changes; only the hook answers differ --

Real scenario: framework base classes that let you plug in your own product: a notification base class with a createChannel() hook; a report generator whose createExporter() returns CSV or PDF; a queue consumer base with newHandler(); in Go, http.Server takes a ConnContext/BaseContext function, and database/sql lets a driver produce connections through driver.Connector (sql.OpenDB(c driver.Connector)), both function- or interface-valued creation hooks.

Go: Go has no inheritance, so the "subclass" becomes an interface value or a function field. That is simpler, and a closure is enough in tests.

go
// Package factorymethod: the GoF Factory Method without inheritance.
// The Creator (Notifier) runs the business flow and calls a creation hook;
// concrete creators decide which product the hook returns.
package factorymethod

import (
	"context"
	"fmt"
	"strings"
)

// Product.
type Channel interface {
	Send(ctx context.Context, to, body string) error
}

// Creator role: the "factory method" is NewChannel.
type ChannelCreator interface {
	NewChannel() Channel
}

// Notifier owns the algorithm; it never names a concrete channel.
type Notifier struct{ creator ChannelCreator }

func NewNotifier(c ChannelCreator) *Notifier { return &Notifier{creator: c} }

func (n *Notifier) Notify(ctx context.Context, to, body string) error {
	if strings.TrimSpace(to) == "" {
		return fmt.Errorf("notify: empty recipient")
	}
	ch := n.creator.NewChannel() // the factory method call
	return ch.Send(ctx, to, body)
}

// Concrete products.
type email struct{ from string }
type sms struct{ senderID string }

func (e *email) Send(ctx context.Context, to, body string) error { return nil }
func (s *sms) Send(ctx context.Context, to, body string) error   { return nil }

// Concrete creators.
type EmailCreator struct{ From string }

func (c EmailCreator) NewChannel() Channel { return &email{from: c.From} }

type SMSCreator struct{ SenderID string }

func (c SMSCreator) NewChannel() Channel { return &sms{senderID: c.SenderID} }

// The Go shortcut: a function type satisfies the creator role,
// so tests and main can pass a closure instead of declaring a type.
type ChannelFunc func() Channel

func (f ChannelFunc) NewChannel() Channel { return f() }

Laravel: the textbook form with an abstract method, plus static factory methods (Money::of()) for contrast.

php
<?php

namespace App\Notifications;

use App\Notifications\Channels\Channel;
use App\Notifications\Channels\MailChannel;
use App\Notifications\Channels\SmsChannel;
use InvalidArgumentException;

// Creator: owns the algorithm, defers "which channel" to a subclass.
abstract class Notifier
{
    // The factory method.
    abstract protected function createChannel(): Channel;

    public function notify(string $to, string $text): void
    {
        if (trim($to) === '') {
            throw new InvalidArgumentException('Empty recipient.');
        }

        $this->createChannel()->send($to, $this->decorate($text));
    }

    protected function decorate(string $text): string
    {
        return $text;
    }
}

final class MailNotifier extends Notifier
{
    protected function createChannel(): Channel
    {
        return new MailChannel(config('mail.from.address'));
    }
}

final class SmsNotifier extends Notifier
{
    protected function createChannel(): Channel
    {
        return new SmsChannel(config('services.sms.sender_id'));
    }

    protected function decorate(string $text): string
    {
        return mb_substr($text, 0, 160);
    }
}

// Static factory methods (not the GoF pattern, but the everyday Laravel idiom):
// Model::factory(), Carbon::now(), Http::withToken(), Money::of().
final class Money
{
    private function __construct(public readonly int $minor, public readonly string $currency) {}

    public static function of(int $minor, string $currency): self
    {
        return new self($minor, strtoupper($currency));
    }

    public static function zero(string $currency): self
    {
        return new self(0, strtoupper($currency));
    }
}

Consequences: the creator is closed for modification and open for new products (OCP); creation is isolated per subclass; but each product needs its own creator subclass ("subclasses proliferate", in the GoF wording quoted above), and inheritance couples the subclass to the base.

When not to use it: when you could pass the product (or a function that makes it) as a constructor argument; that is composition, and in Go and in DI-heavy Laravel it almost always wins.

Related: Template Method (the creator's algorithm is a template method); Abstract Factory (often a set of factory methods); Prototype (an alternative that needs no subclass).

Abstract Factory Must-know ​

In plain words: one object that creates several related things, all from the same "family", so you can never accidentally combine a piece from family A with a piece from family B.

Common misunderstanding: "An abstract class with a create() method is an Abstract Factory." Refactoring.guru: "a lot of people mix-up the abstract factory pattern with a simple factory class declared as abstract. Don't do that!" The defining feature is several product types that must match.

Definition: refactoring.guru: "Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes." GoF (via Wikipedia): "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."

Client«interface» Abstract FactoryNotificationKitsms(): SmsSender mail(): MailSenderformatter(): FormatterIranKitGlobalKit«interface» SmsSender«interface» FormatterFamily: IranLocalGatewaySms, SmtpMail(local)PersianFormatter (rtl, IRR)Family: GlobalGlobalSms, SmtpMail(global)EnglishFormatter (ltr, USD)One kit = one consistent family. Chosen once by config, container or contextual binding.usesuses products via interfacescreatescreates
ParticipantRoleExample
Abstract factoryInterface with one method per productNotificationKit: sms(), mail(), formatter()
Concrete factoryOne per familyIranKit, GlobalKit, FakeKit
Abstract productsOne interface per product typeSmsSender, MailSender, Formatter
Concrete productsMembers of a familyLocalGatewaySms + PersianFormatter; GlobalSms + EnglishFormatter
ClientUses only the interfacesReceiptSender
text
     Step  Without a kit                                     With NotificationKit
1          sms = new LocalGatewaySms(key)                    kit = container picks IranKit (config: region=ir)
2          fmt = new EnglishFormatter()   <-- wrong family   sms = kit.sms(); fmt = kit.formatter()
3          send("Paid $12.50") to an Iranian number          send("Paid 125,000 IRR")
4          bug found by customers                            mixing is impossible: one kit, one family

Real scenario: per-region provider families (local SMS gateway, local mail relay, local formatting); per-cloud families (AWS: S3 + SQS + KMS clients, GCP: GCS + Pub/Sub + Cloud KMS); UI toolkits (the GoF example: widgets per look-and-feel); test vs sandbox vs live families of payment, mail and SMS clients.

Go: an interface with several constructors; clients receive the kit.

go
// Package abstractfactory: one interface that creates a whole family of
// products that must be used together (sender + formatter per region).
package abstractfactory

import (
	"context"
	"fmt"
)

// Abstract products.
type EmailSender interface {
	SendEmail(ctx context.Context, to, subject, html string) error
}
type SMSSender interface {
	SendSMS(ctx context.Context, to, text string) error
}
type Formatter interface {
	Money(cents int64) string
	Direction() string // "ltr" or "rtl"
}

// Abstract factory.
type Kit interface {
	Email() EmailSender
	SMS() SMSSender
	Formatter() Formatter
}

// Family 1: Iran region (local SMS gateway, Persian formatting).
type IranKit struct{ GatewayKey string }

func (k IranKit) Email() EmailSender   { return localMail{} }
func (k IranKit) SMS() SMSSender       { return localSMS{key: k.GatewayKey} }
func (k IranKit) Formatter() Formatter { return faFormatter{} }

// Family 2: global region (international providers, English formatting).
type GlobalKit struct{ APIKey string }

func (k GlobalKit) Email() EmailSender   { return globalMail{} }
func (k GlobalKit) SMS() SMSSender       { return globalSMS{key: k.APIKey} }
func (k GlobalKit) Formatter() Formatter { return enFormatter{} }

// Concrete products (bodies trimmed; real ones call HTTP APIs).
type localMail struct{}
type localSMS struct{ key string }
type globalMail struct{}
type globalSMS struct{ key string }
type faFormatter struct{}
type enFormatter struct{}

func (localMail) SendEmail(ctx context.Context, to, subject, html string) error  { return nil }
func (localSMS) SendSMS(ctx context.Context, to, text string) error              { return nil }
func (globalMail) SendEmail(ctx context.Context, to, subject, html string) error { return nil }
func (globalSMS) SendSMS(ctx context.Context, to, text string) error             { return nil }
func (faFormatter) Money(c int64) string                                         { return fmt.Sprintf("%d IRR", c/100) }
func (faFormatter) Direction() string                                            { return "rtl" }
func (enFormatter) Money(c int64) string                                         { return fmt.Sprintf("$%d.%02d", c/100, c%100) }
func (enFormatter) Direction() string                                            { return "ltr" }

// Client code sees only the Kit; it cannot mix an Iran SMS with an English formatter.
func SendReceipt(ctx context.Context, kit Kit, phone string, cents int64) error {
	f := kit.Formatter()
	return kit.SMS().SendSMS(ctx, phone, "Paid "+f.Money(cents))
}

Laravel: the kit is an interface bound in a service provider; contextual binding gives a different family to different consumers, which is an Abstract Factory configured by the container. Laravel 13 docs: "two controllers may depend on different implementations of the Illuminate\Contracts\Filesystem\Filesystem contract. Laravel provides a simple, fluent interface for defining this behavior": when()->needs()->give().

php
<?php

namespace App\Notifications\Kits;

// Abstract products.
interface SmsSender
{
    public function sendSms(string $to, string $text): void;
}

interface MailSender
{
    public function sendMail(string $to, string $subject, string $html): void;
}

interface Formatter
{
    public function money(int $minor): string;

    public function direction(): string;
}

// Abstract factory: one family per region.
interface NotificationKit
{
    public function sms(): SmsSender;

    public function mail(): MailSender;

    public function formatter(): Formatter;
}

final class IranKit implements NotificationKit
{
    public function __construct(private string $gatewayKey) {}

    public function sms(): SmsSender
    {
        return new LocalGatewaySms($this->gatewayKey);
    }

    public function mail(): MailSender
    {
        return new SmtpMail('mail.local');
    }

    public function formatter(): Formatter
    {
        return new PersianFormatter();
    }
}

final class GlobalKit implements NotificationKit
{
    public function __construct(private string $apiKey) {}

    public function sms(): SmsSender
    {
        return new GlobalSms($this->apiKey);
    }

    public function mail(): MailSender
    {
        return new SmtpMail('smtp.global.example');
    }

    public function formatter(): Formatter
    {
        return new EnglishFormatter();
    }
}

final class LocalGatewaySms implements SmsSender
{
    public function __construct(private string $key) {}

    public function sendSms(string $to, string $text): void { /* Http::withToken($this->key)->post(...) */ }
}

final class GlobalSms implements SmsSender
{
    public function __construct(private string $key) {}

    public function sendSms(string $to, string $text): void { /* ... */ }
}

final class SmtpMail implements MailSender
{
    public function __construct(private string $host) {}

    public function sendMail(string $to, string $subject, string $html): void { /* ... */ }
}

final class PersianFormatter implements Formatter
{
    public function money(int $minor): string
    {
        return number_format(intdiv($minor, 100)).' IRR';
    }

    public function direction(): string
    {
        return 'rtl';
    }
}

final class EnglishFormatter implements Formatter
{
    public function money(int $minor): string
    {
        return '$'.number_format($minor / 100, 2);
    }

    public function direction(): string
    {
        return 'ltr';
    }
}

// Client: sees only the kit, so it cannot mix families.
final class ReceiptSender
{
    public function __construct(private NotificationKit $kit) {}

    public function send(string $phone, int $minor): void
    {
        $this->kit->sms()->sendSms($phone, 'Paid '.$this->kit->formatter()->money($minor));
    }
}

Consequences: families stay consistent; switching family is one line; but adding a new product type (say push()) changes the interface and every concrete factory.

When not to use it: when products do not actually need to match (inject them separately); when there is only one family and no test double; when the "family" is really configuration values (pass a config struct).

Related: concrete factories are often singletons; each method is often a factory method; a kit can hold prototypes and clone them.

Builder Must-know ​

In plain words: build a complicated object in steps (set this, add that), then call build() once, which checks everything and hands you a finished, valid object.

Common misunderstanding: "Builder is just method chaining." Chaining (a fluent interface) is the syntax. The pattern is about separating construction from the product: the product is not usable until build(), invariants are checked in one gate, and the same steps can produce different representations. A fluent setter on a live object is not a builder.

Definition: refactoring.guru: "Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code." The optional Director "defines the order in which to execute the building steps, while the builder provides the implementation for those steps."

DirectorSecurityMessages::otp()SmsMessageBuilderto(phone): selfline(text): selfurgent(): self tag(t): selfbuild(): validate, then createSmsMessageimmutable productGo variant: functional options (Pike 2014, Cheney 2014)defaults: 5s, 2 retriesWithTimeout(3s)WithRetries(3)*Client readyBuilder separates how an object is assembled from what it is; build() is the single validation gate.stepsreturns
ParticipantRoleExample
BuilderStep methods, accumulates stateSmsMessageBuilder, MessageBuilder
build() / Build()Single validation gate, returns the productthrows InvalidArgumentException / returns (Message, error)
ProductFinished, ideally immutableSmsMessage with readonly properties
Director (optional)Named recipe over the stepsSecurityMessages::otp(), builder.PasswordReset()
Functional option (Go)A function that sets one fieldWithTimeout(3*time.Second)
text
     Step  Telescoping constructor                                   Builder
1          new Sms('+98...', 'hi', 5, null, [], false, null, 'fa')    SmsMessageBuilder::create()
2          -- which argument is priority? which is sendAt? --          ->to('+98...')->line('hi')
3          forgot one: TypeError at runtime                            ->urgent()->tag('otp')
4          invalid combination accepted silently                       ->build()  // validates once, or throws

Refactoring.guru names the classic trigger: "Use the Builder pattern to get rid of a 'telescoping constructor'", that is, "a constructor with ten optional parameters".

Real scenario: Laravel's query builder ("a convenient, fluent interface to creating and running database queries"); Laravel's HTTP client (Http::withToken()->timeout(3)->retry(3, 100)->post()); MailMessage (->subject()->line()->action()); Eloquent model factories (User::factory()->count(3)->suspended()->create()); in Go, http.NewRequestWithContext plus setters, gRPC's grpc.NewClient(target, opts...) and many SDKs that take functional options; SQL builders such as squirrel.

Go: two shapes. Functional options when you configure a long-lived object (Cheney's NewServer(addr, opts...) shape); a step builder with Build() (T, error) when you assemble a value with invariants.

go
// Package builder shows the two Go shapes of Builder:
// functional options for configuring a long-lived object (Pike 2014, Cheney 2014),
// and a step builder with Build() for assembling a validated value.
package builder

import (
	"errors"
	"net/http"
	"strings"
	"time"
)

// ---- Functional options: Client is configured once, at construction ----

type Client struct {
	baseURL string
	timeout time.Duration
	retries int
	token   string
	http    *http.Client
}

// Option mutates a Client under construction.
type Option func(*Client)

func WithTimeout(d time.Duration) Option { return func(c *Client) { c.timeout = d } }
func WithRetries(n int) Option           { return func(c *Client) { c.retries = n } }
func WithToken(t string) Option          { return func(c *Client) { c.token = t } }

// NewClient has sensible defaults; the zero-option call is the common case.
func NewClient(baseURL string, opts ...Option) *Client {
	c := &Client{baseURL: baseURL, timeout: 5 * time.Second, retries: 2}
	for _, opt := range opts {
		opt(c)
	}
	c.http = &http.Client{Timeout: c.timeout}
	return c
}

// ---- Step builder: Message is assembled, validated, then immutable ----

type Message struct {
	To       []string
	Subject  string
	Body     string
	Priority int
	Tags     []string
}

type MessageBuilder struct {
	msg  Message
	errs []error
}

func NewMessage() *MessageBuilder { return &MessageBuilder{msg: Message{Priority: 5}} }

func (b *MessageBuilder) To(addr string) *MessageBuilder {
	if !strings.Contains(addr, "@") && !strings.HasPrefix(addr, "+") {
		b.errs = append(b.errs, errors.New("invalid recipient "+addr))
	}
	b.msg.To = append(b.msg.To, addr)
	return b
}

func (b *MessageBuilder) Subject(s string) *MessageBuilder { b.msg.Subject = s; return b }
func (b *MessageBuilder) Body(s string) *MessageBuilder    { b.msg.Body = s; return b }
func (b *MessageBuilder) Urgent() *MessageBuilder          { b.msg.Priority = 1; return b }
func (b *MessageBuilder) Tag(t string) *MessageBuilder {
	b.msg.Tags = append(b.msg.Tags, t)
	return b
}

// Build checks the invariants once and returns a copy the caller cannot
// change through the builder.
func (b *MessageBuilder) Build() (Message, error) {
	if len(b.msg.To) == 0 {
		b.errs = append(b.errs, errors.New("no recipient"))
	}
	if b.msg.Body == "" {
		b.errs = append(b.errs, errors.New("empty body"))
	}
	if err := errors.Join(b.errs...); err != nil {
		return Message{}, err
	}
	m := b.msg
	m.To = append([]string(nil), b.msg.To...)
	m.Tags = append([]string(nil), b.msg.Tags...)
	return m, nil
}

// Director: a reusable recipe over the builder steps.
func PasswordReset(to, link string) (Message, error) {
	return NewMessage().To(to).Subject("Reset your password").
		Body("Open " + link + " within 30 minutes.").Urgent().Tag("security").Build()
}

Laravel: a fluent builder with a director, and the builders you already use every day.

php
<?php

namespace App\Notifications\Messages;

use InvalidArgumentException;

// Product: immutable once built.
final class SmsMessage
{
    /** @param list<string> $tags */
    public function __construct(
        public readonly string $to,
        public readonly string $text,
        public readonly int $priority,
        public readonly ?\DateTimeImmutable $sendAt,
        public readonly array $tags,
    ) {}
}

// Builder: fluent steps, validation in build().
final class SmsMessageBuilder
{
    private ?string $to = null;
    private string $text = '';
    private int $priority = 5;
    private ?\DateTimeImmutable $sendAt = null;
    /** @var list<string> */
    private array $tags = [];

    public static function create(): self
    {
        return new self();
    }

    public function to(string $phone): self
    {
        $this->to = $phone;

        return $this;
    }

    public function line(string $text): self
    {
        $this->text = trim($this->text.' '.$text);

        return $this;
    }

    public function urgent(): self
    {
        $this->priority = 1;

        return $this;
    }

    public function at(\DateTimeImmutable $when): self
    {
        $this->sendAt = $when;

        return $this;
    }

    public function tag(string $tag): self
    {
        $this->tags[] = $tag;

        return $this;
    }

    public function build(): SmsMessage
    {
        if ($this->to === null || ! str_starts_with($this->to, '+')) {
            throw new InvalidArgumentException('SMS needs an E.164 recipient.');
        }
        if ($this->text === '' || mb_strlen($this->text) > 160) {
            throw new InvalidArgumentException('SMS text must be 1..160 characters.');
        }

        return new SmsMessage($this->to, $this->text, $this->priority, $this->sendAt, $this->tags);
    }
}

// Director: a named recipe over the builder.
final class SecurityMessages
{
    public static function otp(string $phone, string $code): SmsMessage
    {
        return SmsMessageBuilder::create()
            ->to($phone)
            ->line("Your code is {$code}.")
            ->line('It expires in 2 minutes.')
            ->urgent()
            ->tag('otp')
            ->build();
    }
}

// Builders you already use in Laravel 13 (each call returns a configured builder):
//
//   DB::table('users')->where('active', true)->orderBy('id')->limit(50)->get();
//   Http::withToken($token)->timeout(3)->retry(3, 100)->post($url, $payload);
//   (new MailMessage)->subject('Invoice paid')->line('Thanks!')->action('View', $url);
//   User::factory()->count(3)->suspended()->create();

Consequences: readable construction; invariants in one place; immutable products; but more code than a constructor, and a mutable builder shared between goroutines or requests is a bug waiting to happen.

When not to use it: for objects with two or three required fields (use a constructor with named arguments in PHP 8 or a struct literal with field names in Go); for configuration that is really a struct (pass a Config struct; Cheney discusses this trade-off).

Related: Abstract Factory returns the product immediately, Builder in steps; a builder can be used by a Director that is itself a Factory Method; builders often build Composites.

Prototype Important ​

In plain words: keep a fully configured example object around and make new objects by copying it, then change the few things that differ.

Common misunderstanding: "clone copies the whole object." In PHP, "When an object is cloned, PHP will perform a shallow copy of all of the object's properties"; in Go, c := *t copies the struct but maps, slices and pointers inside still point at the same data. A prototype without a deep copy leaks changes back into the template.

Definition: refactoring.guru: "Prototype is a creational design pattern that lets you copy existing objects without making your code dependent on their classes." A prototype registry "stores a set of pre-built objects that are ready to be copied. The simplest prototype registry is a name → prototype hash map."

ClientPrototype registry"receipt" → prototype"otp" → prototypemake(name) = clone(prototype)copyowned by the callerShallow copy (Go *t, PHP clone)originalcopyshared mapDeep copy (Clone, __clone)originalcopyown mapown mapmake(name)clone()
ParticipantRoleGoPHP
PrototypeDeclares the copy operationClone() *Templateclone + __clone()
Concrete prototypeCopies itself, deep where neededmaps.Clone, slices.Clone__clone() clones nested objects
Registry (optional)Name → prototypeRegistry.New(name)TemplateRegistry::make()
ClientAsks for a copy and tweaks itTenant onboardingforTenant('acme')
text
     Step  Shallow copy (bug)                                  Deep copy (Clone / __clone)
1          base.Headers = {X-Brand: acme}                      same
2          c := *base; c.Headers["X-Brand"] = "tenant-42"      c := base.Clone(); c.Headers["X-Brand"] = "tenant-42"
3          base.Headers["X-Brand"] == "tenant-42"  <-- leaked  base.Headers["X-Brand"] == "acme"
4          every later tenant gets the wrong brand              each copy owns its map

Real scenario: per-tenant notification templates cloned from a parsed base; game entities spawned from a configured archetype; Eloquent's replicate() ("You may create an unsaved copy of an existing model instance using the replicate method"); http.Request.Clone(ctx) in Go's net/http; PSR-7 immutable withHeader() methods that return modified copies; test fixtures copied from a canonical object.

Go: an explicit Clone() that deep-copies maps and slices, plus a test that shows the shallow copy leaking.

go
// Package prototype: copy a configured object instead of rebuilding it,
// and make the copy deep where it holds maps and slices.
package prototype

import (
	"fmt"
	"maps"
	"slices"
)

// Template is costly to build: parsed layout, default headers, channel list.
type Template struct {
	Name     string
	Layout   string
	Headers  map[string]string
	Channels []string
}

// ShallowCopy shows the bug: the copy shares the map and the slice array.
func (t *Template) ShallowCopy() *Template {
	c := *t
	return &c
}

// Clone is the Prototype operation: a deep copy that owns its own data.
func (t *Template) Clone() *Template {
	return &Template{
		Name:     t.Name,
		Layout:   t.Layout,
		Headers:  maps.Clone(t.Headers),
		Channels: slices.Clone(t.Channels),
	}
}

// Registry keeps ready-made prototypes by name and hands out copies.
type Registry struct{ protos map[string]*Template }

func NewRegistry() *Registry { return &Registry{protos: map[string]*Template{}} }

func (r *Registry) Register(p *Template) { r.protos[p.Name] = p }

func (r *Registry) New(name string) (*Template, error) {
	p, ok := r.protos[name]
	if !ok {
		return nil, fmt.Errorf("prototype %q not registered", name)
	}
	return p.Clone(), nil
}
go
package prototype

import "testing"

func TestCloneIsDeep(t *testing.T) {
	base := &Template{Name: "receipt", Headers: map[string]string{"X-Brand": "acme"}, Channels: []string{"mail"}}
	shallow := base.ShallowCopy()
	shallow.Headers["X-Brand"] = "changed"
	if base.Headers["X-Brand"] != "changed" {
		t.Fatal("expected the shallow copy to share the map")
	}
	base.Headers["X-Brand"] = "acme"
	deep := base.Clone()
	deep.Headers["X-Brand"] = "tenant-42"
	deep.Channels[0] = "sms"
	if base.Headers["X-Brand"] != "acme" || base.Channels[0] != "mail" {
		t.Fatal("clone leaked into the prototype")
	}
}

Laravel / PHP 8.4: __clone() deepens the copy; readonly value objects use "withers". PHP 8.5 adds clone($this, ['city' => $city]): the manual says "the overrides are applied after __clone() has run" and "Readonly properties can be updated on the copy".

php
<?php

namespace App\Notifications\Templates;

final class Recipient
{
    public function __construct(public string $name, public string $email) {}
}

final class EmailTemplate
{
    /**
     * @param array<string, string> $headers
     * @param list<Recipient> $cc
     */
    public function __construct(
        public string $name,
        public string $layout,
        public array $headers,
        public array $cc,
        public \DateTimeImmutable $createdAt,
    ) {}

    // clone is shallow: arrays are copied by value, but objects inside them
    // (Recipient) are shared handles. __clone runs on the copy to deepen it.
    public function __clone(): void
    {
        $this->cc = array_map(fn (Recipient $r) => clone $r, $this->cc);
        // DateTimeImmutable never changes, so sharing it is safe.
    }

    public function forTenant(string $brand): self
    {
        $copy = clone $this;
        $copy->headers['X-Brand'] = $brand;

        return $copy;
    }
}

// Prototype registry: pre-built templates handed out as copies.
final class TemplateRegistry
{
    /** @var array<string, EmailTemplate> */
    private array $prototypes = [];

    public function register(EmailTemplate $prototype): void
    {
        $this->prototypes[$prototype->name] = $prototype;
    }

    public function make(string $name): EmailTemplate
    {
        $prototype = $this->prototypes[$name]
            ?? throw new \InvalidArgumentException("Template [{$name}] not registered.");

        return clone $prototype;
    }
}

// Readonly value objects: a "wither" returns a modified copy.
final class Address
{
    public function __construct(public readonly string $city, public readonly string $zip) {}

    // PHP 8.4: build a new instance (readonly props cannot be written after clone
    // outside __clone).
    public function withCity(string $city): self
    {
        return new self($city, $this->zip);
    }

    // PHP 8.5+: clone() as a function with property overrides:
    //   return clone($this, ['city' => $city]);
}

// Eloquent's own prototype: $model->replicate() copies attributes into a new,
// unsaved model (no primary key, no timestamps).
//   $draft = $invoice->replicate()->fill(['status' => 'draft']);

Consequences: cheap creation of pre-configured objects; no subclass per variant; but deep copy is your job, cycles and resources (file handles, sockets, DB connections) must not be copied, and identity-based code may break.

When not to use it: when construction is cheap (just call the constructor); when objects hold resources; when a builder with a director expresses the variants more clearly.

Related: an Abstract Factory can store prototypes and clone them; designs heavy in Composite and Decorator benefit from Prototype (GoF, via Wikipedia).

Supporting concepts ​

Static factory method and named constructors Must-know ​

In plain words: a static method (PHP) or package-level function (Go) with a good name that returns a new instance: Money::of(100, 'EUR'), Carbon::now(), time.Unix(0, 0), errors.New("x").

Common misunderstanding: "That is the Factory Method pattern." It is not; there is no hook. It is the most common creational tool in real code anyway, because a name says more than new and can return a cached instance, a subtype, or an error.

Definition: Effective Go describes constructors as plain functions: "the function to make new instances of ring.Ring—which is the definition of a constructor in Go—would normally be called NewRing", or just New when the package exports one type. Laravel models expose User::factory() via the HasFactory trait; PHP enums use static methods as "alternative constructors".

FormExampleWhy a name helps
Go New / NewTbufio.NewReader(r), ring.New(n)Validates input, sets defaults, returns an error
Go zero valuevar mu sync.MutexNo constructor at all: "the zero value for a sync.Mutex is defined to be an unlocked mutex" (Effective Go)
PHP named constructorMoney::of(), Money::zero()Two constructors with different meaning
PHP enum staticSize::fromLength(120)Mapping input to a case
LaravelUser::factory(), Http::withToken(), Str::of()Entry point to a builder

Lazy initialization Important ​

In plain words: do not build an expensive object until somebody actually uses it.

Common misunderstanding: "Lazy is always faster." It moves the cost to the first request (cold-start latency spike) and moves errors from startup to runtime: a wrong DSN is discovered by the first customer, not by the deploy.

Definition: creation deferred until first access, made thread-safe. Go: sync.Once ("an object that will perform exactly one action") or Go 1.21's OnceValue, which the release notes say "capture a common use of Once to lazily initialize a value on first use". PHP 8.4: "A lazy object is an object whose initialization is deferred until its state is observed or modified", in two strategies, "Ghost Objects and Virtual Proxies"; "Lazy objects were introduced in PHP 8.4." Laravel: deferred service providers and closures in bind()/singleton() already delay construction until first make().

text
     Request  Eager (build in main)                       Lazy (OnceValue / closure binding)
1    boot     connect to SMS gateway: 300 ms, fail fast   nothing
2    #1       send: 5 ms                                  first use: connect 300 ms + send 5 ms
3    #2       send: 5 ms                                  send: 5 ms
4    bad key  deploy fails health check                   first customer gets a 500

Object pool Good to know ​

In plain words: keep a set of already-built objects and lend them out instead of creating new ones.

Common misunderstanding: "Pool everything to save memory." Pools add bugs (forgetting to reset, using an object after returning it) and only pay off for expensive or very frequent allocations. Go's docs: sync.Pool "is not suitable for all free lists".

Definition: Go sync.Pool: "A Pool is a set of temporary objects that may be individually saved and retrieved. Any item stored in the Pool may be removed automatically at any time without notification." Its "purpose is to cache allocated but unused items for later reuse, relieving pressure on the garbage collector"; the standard example is fmt's output buffers. Connection pools (database/sql's *sql.DB, PgBouncer, Laravel's per-worker PDO under Octane) are object pools for connections; see Connection Pooling.

go
// Package pool: an object pool for short-lived, allocation-heavy values.
package pool

import (
	"bytes"
	"sync"
)

var buffers = sync.Pool{New: func() any { return new(bytes.Buffer) }}

// Render borrows a buffer, uses it, resets it and gives it back.
// Never keep a reference to a pooled object after Put.
func Render(name, body string) string {
	buf := buffers.Get().(*bytes.Buffer)
	defer func() {
		buf.Reset()
		buffers.Put(buf)
	}()
	buf.WriteString("Hello ")
	buf.WriteString(name)
	buf.WriteString(",\n\n")
	buf.WriteString(body)
	return buf.String() // String copies, so returning it is safe
}

Registry and Multiton Good to know ​

In plain words: a well-known map from a name to an object or a constructor; a Multiton is a singleton per key.

Common misunderstanding: "A registry is a service locator, so it is always bad." A registry of plugins populated at startup (drivers, codecs, channels) is a fine extension point. It becomes the anti-pattern when business code pulls its dependencies from it.

Definition: Fowler (Patterns of Enterprise Application Architecture catalog): "A well-known object that other objects can use to find common objects and services." Go's database/sql is the canonical example: "Register makes a database driver available by the provided name. If Register is called twice with the same name or if driver is nil, it panics." Drivers call sql.Register in init(), and sql.Open("pgx", dsn) looks the factory up by name. Laravel's Illuminate\Support\Manager is a registry-plus-factory: driver($name) caches instances ($this->drivers[$driver] ??= $this->createDriver($driver)), calls a create{Name}Driver() method or a closure registered with extend(), and throws Driver [x] not supported. otherwise. Cache, session, mail and notification channels are all built this way.

Dependency injection and the composition root Must-know ​

In plain words: a class receives the things it needs (usually through its constructor) instead of creating or looking them up; all the creating happens in one place at the edge of the program.

Common misunderstanding: "DI needs a container." In Go the composition root is main and DI is passing arguments. A container (Laravel's, Spring's, .NET's) automates the wiring; it does not change the principle.

Definition: DI is the modern home for most creational decisions: lifetime (singleton/scoped/transient) is a container setting; "which implementation" is a binding or a switch in main; families are a bound kit. Laravel 13: "Laravel's service container implements the PSR-11 interface", resolves classes with "zero configuration" when they need only concrete types, and lets you bind, singleton, scoped, instance, extend, tag, and when()->needs()->give(). Factories survive inside the composition root.

Service locator (anti-pattern) Important ​

In plain words: instead of receiving dependencies, a class asks a global object for them in the middle of its methods: app(Mailer::class), ServiceLocator::get('mailer').

Common misunderstanding: "Laravel facades and app() are service locators, so Laravel is an anti-pattern." They can be used that way. Constructor injection in your own classes, with app()/make() limited to providers, factories and framework edges, keeps the composition root intact. Fowler (2004) treated locator and injection as alternatives; Seemann (2010) argues the locator is an anti-pattern because it "hides a class' dependencies, causing run-time errors instead of compile-time errors".

Definition: a registry used as the dependency-acquisition mechanism inside business code. Symptoms: constructors with no parameters, tests that must configure a global container, BindingResolutionException in production for a path no test covered.

text
     Step  Constructor injection                         Service locator inside a method
1    boot  container builds OrderService(Mailer, Sms)    container builds OrderService()
2    test  new OrderService(new FakeMailer, new FakeSms)  must bind fakes in the global container first
3    prod  missing binding: fails when the class is built missing binding: fails when ship() runs at 03:00
4    read  signature lists every dependency              open the method body to find out

Test data builders, Object Mother and model factories Important ​

In plain words: creational patterns for tests: build valid example objects quickly, override only what the test is about.

Common misunderstanding: "One giant fixture file is simpler." Shared fixtures couple every test to every field; a builder with valid defaults lets each test state only the field it cares about.

Definition: Fowler: "An object mother is a kind of class used in testing to help create example objects that you use for testing." A test data builder is a Builder with valid defaults. Laravel's Eloquent factories are both: "Laravel allows you to define a set of default attributes for each of your Eloquent models using model factories"; states are named variations; make() builds in memory, create() persists. In Go, the same job is done by functions such as newTestUser(t, func(u *User) { u.Locale = "fa" }), the functional-options shape applied to test data.

php
<?php

// Creation for tests: Eloquent factories (Laravel's builder + prototype for
// models), a test data builder, and an object mother.

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/** @extends Factory<User> */
class UserFactory extends Factory
{
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'phone' => '+98912'.fake()->numerify('#######'),
            'prefers_sms' => false,
            'locale' => 'en',
        ];
    }

    // States: named variations applied on top of the definition.
    public function prefersSms(): static
    {
        return $this->state(fn (array $attributes) => ['prefers_sms' => true]);
    }

    public function persian(): static
    {
        return $this->state(fn (array $attributes) => ['locale' => 'fa']);
    }
}

// Usage:
//   User::factory()->make();                          // in memory, not saved
//   User::factory()->count(3)->prefersSms()->create(); // saved
//   User::factory()->persian()->prefersSms()->create(['name' => 'Sara']);

namespace Tests\Support;

use App\Models\User;
use App\Notifications\Messages\SmsMessage;
use App\Notifications\Messages\SmsMessageBuilder;

// Object mother: named, ready-made examples shared by many tests.
final class Users
{
    public static function iranianSmsCustomer(): User
    {
        return User::factory()->persian()->prefersSms()->make(['phone' => '+989120000000']);
    }
}

// Test data builder: defaults that pass validation; each test overrides one thing.
final class AnSms
{
    private SmsMessageBuilder $b;

    private function __construct()
    {
        $this->b = SmsMessageBuilder::create()->to('+989120000000')->line('hello');
    }

    public static function valid(): self
    {
        return new self();
    }

    public function to(string $phone): self
    {
        $this->b->to($phone);

        return $this;
    }

    public function build(): SmsMessage
    {
        return $this->b->build();
    }
}

Per-language view ​

Language / frameworkConstructorSingleton / lifetimeFactoryBuilderPrototype
GoNewT(...) function, zero values, composite literalsBuild once in main; sync.Once, sync.OnceValueFunction returning an interface; func() T fields; sql.Register registryFunctional options; step builder with Build()Explicit Clone(); maps.Clone, slices.Clone; http.Request.Clone
PHP 8.4 / Laravel 13__construct with promoted properties; named argumentsContainer singleton, scoped, instance; #[Singleton], #[Scoped]match factories, enum make(), Manager::driver(), contextual bindingQuery builder, PendingRequest (HTTP), MailMessage, model factoriesclone + __clone(), replicate(), PHP 8.5 clone($o, [...])
Java / Springnew, constructors, records@Scope("singleton") default, prototype, request@Bean methods, FactoryBean, ServiceLoaderLombok @Builder, StringBuilder, HttpRequest.newBuilder()Cloneable (widely considered flawed), copy constructors
C# / .NETConstructors, object initializersAddSingleton, AddScoped, AddTransient; Lazy<T>IServiceProvider, IHttpClientFactory, factory delegatesWebApplication.CreateBuilder(), StringBuilderMemberwiseClone() (shallow), records with with
TypeScript / Nodeconstructor, object literalsModule cache makes every module a singletonFactory functions, NestJS providers (useFactory)Fluent builders (Knex, Prisma query API)structuredClone(), spread {...obj} (shallow)
Python__init__, @classmethod alternative constructorsModule-level instance; functools.cacheFunctions, @classmethod from_xKeyword arguments usually replace builderscopy.copy / copy.deepcopy

Mechanics ​

Thread safety of singletons and lazy values Must-know ​

RuntimeHow "one instance" can breakSafe idiom
GoCheck-then-set on a package var from several goroutines (data race; go test -race catches it)sync.Once, sync.OnceValue; or build in main before starting goroutines
JavaDouble-checked locking without volatile (pre-Java 5 memory model)Holder-class idiom, enum singleton, or a DI container
.NETSame as JavaLazy<T> (thread-safe by default), AddSingleton
PHP-FPMNot a threading issue: each request is a fresh process state, so a static singleton lives for one requestFine for per-request caches; useless as a cross-request cache
PHP under Octane / queue workers / Swoole / RoadRunnerOne worker serves many requests; a static or container singleton keeps request data (user, tenant, locale) across requestsscoped() for per-request state; never inject Request or the container into a singleton (Octane docs: such an object "may have a stale version of the container or request on subsequent requests")
Node.jsSingle-threaded event loop; module singletons are shared by every concurrent requestKeep per-request state in request scope (AsyncLocalStorage)

Go's memory-model guarantee is what makes sync.Once correct: "the return from f 'synchronizes before' the return from any call of once.Do(f)". Two more rules from the sync docs: "A Once must not be copied after first use", and values from the sync package "should not be copied" in general.

Container lifetimes and resolution in Laravel 13 Must-know ​

APILifetimeTypical use
bind(Abstract::class, fn () => ...)New object per resolutionStateful helpers, builders
bindIf() / singletonIf()Only if nothing is bound yetPackage defaults the app can override
singleton() / #[Singleton]One per application instance (one per worker under Octane)Stateless API clients, config-derived services
scoped() / #[Scoped]One per request or queued job; flushed on a new Octane request or jobTenant context, per-request caches
instance($abstract, $object)The given object, alwaysTests ($this->app->instance(...)), pre-built objects
#[Bind(Impl::class)], #[Bind(Fake::class, environments: ['local', 'testing'])]Default implementation declared on the interfaceEnvironment-driven creation without a provider
#[BindWhen(Impl::class, fn () => Feature::active('beta-events'))]Conditional binding (docs: "requires PHP 8.5 or greater")Feature-flagged implementations via Laravel Pennant
when(A::class)->needs(I::class)->give(...)Per-consumer implementationAbstract Factory per controller/job
extend(I::class, fn ($service, $app) => ...)Decorates what was createdLogging/metrics decorators
tag([...], 'reports') + tagged('reports')Collection of bindingsPlugin lists, all notification channels
make(), makeWith(X::class, ['id' => 1]), app()Resolve nowProviders, factories, framework edges only

Error messages you will see Important ​

Message (verbatim from source)WhereMeaningFix
sql: unknown driver "pgx" (forgotten import?)Go database/sql OpenNo factory registered under that nameBlank-import the driver package (_ "github.com/jackc/pgx/v5/stdlib")
sql: Register called twice for driver pgxGo database/sql Register (panic)Two packages registered the same nameImport one driver per name
sql: Register driver is nilGo database/sql Register (panic)Nil factory registeredBug in the driver's init()
Target [App\Contracts\Kit] is not instantiable.Laravel BindingResolutionExceptionInterface asked for, nothing boundBind it in a provider or add #[Bind]
Target [X] is not instantiable while building [Y].Same, nestedA dependency of Y is an unbound interfaceBind X, or use contextual binding for Y
Unresolvable dependency resolving [Parameter #0 [ <required> string $url ]] in class ...Laravel containerA scalar constructor argument with no defaultBind with a closure, makeWith(), or give() / giveConfig()
Target class [App\Foo] does not exist.Laravel containerTypo or autoload issueFix the class name / composer dump-autoload
Driver [x] not supported.Laravel Manager::createDriver()No createXDriver() method or extend() closureRegister the driver with extend()
Unable to resolve NULL driver for [...]Laravel Manager::driver()No default driver configuredSet the default in config

Configuration-driven creation Important ​

When the choice of product depends on deployment, tenant or a feature flag, the factory reads configuration, not hard-coded constants. A database-backed version, useful in multi-tenant SaaS:

sql
-- Which provider family each tenant uses, read once per request (or cached).
CREATE TABLE notification_providers (
    tenant_id   bigint      NOT NULL,
    channel     text        NOT NULL CHECK (channel IN ('mail', 'sms', 'push')),
    provider    text        NOT NULL,           -- 'local_gateway', 'global_sms', 'ses', ...
    enabled     boolean     NOT NULL DEFAULT true,
    settings    jsonb       NOT NULL DEFAULT '{}',
    updated_at  timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (tenant_id, channel)
);

-- The factory's input for tenant 42:
SELECT channel, provider, settings
FROM notification_providers
WHERE tenant_id = 42 AND enabled;

The factory maps provider to a constructor (a registry), so adding a provider adds a row and a registered constructor, not a new if in business code.

Go ​

Before ​

Creation is mixed into business logic: the function reads environment variables, picks a concrete type with if, and builds it. It cannot be tested without real credentials and cannot get a new channel without editing it.

go
// Package before: creation scattered through business code.
package before

import (
	"context"
	"fmt"
	"os"
)

type smtpMailer struct{ host string }
type twilioSMS struct{ token string }

func (m *smtpMailer) Send(ctx context.Context, to, body string) error { return nil }
func (s *twilioSMS) Send(ctx context.Context, to, body string) error  { return nil }

// OrderShipped decides which concrete class to build, reads env vars itself,
// and cannot be tested without real credentials.
func OrderShipped(ctx context.Context, user map[string]string, orderID int) error {
	body := fmt.Sprintf("Order %d shipped", orderID)
	if user["prefers_sms"] == "1" {
		s := &twilioSMS{token: os.Getenv("TWILIO_TOKEN")} // new #1
		return s.Send(ctx, user["phone"], body)
	}
	m := &smtpMailer{host: os.Getenv("SMTP_HOST")} // new #2
	return m.Send(ctx, user["email"], body)
}

After ​

main is the composition root: it reads configuration once, uses a simple factory to pick the kit (Abstract Factory), configures a client with functional options (Builder), and passes interfaces down.

go
// Command compositionroot: the only place that calls concrete constructors.
// Configuration (env, flags, feature flags) picks the products; everything
// below main receives interfaces.
package main

import (
	"context"
	"log/slog"
	"os"

	"academy/creational-patterns/abstractfactory"
	"academy/creational-patterns/builder"
)

func kitFor(region string) abstractfactory.Kit {
	switch region {
	case "ir":
		return abstractfactory.IranKit{GatewayKey: os.Getenv("SMS_GATEWAY_KEY")}
	default:
		return abstractfactory.GlobalKit{APIKey: os.Getenv("SMS_API_KEY")}
	}
}

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) // one per process
	kit := kitFor(os.Getenv("REGION"))
	api := builder.NewClient("https://billing.internal",
		builder.WithRetries(3), builder.WithToken(os.Getenv("BILLING_TOKEN")))
	_ = api
	if err := abstractfactory.SendReceipt(context.Background(), kit, "+989120000000", 125000); err != nil {
		logger.Error("receipt failed", "err", err)
		os.Exit(1)
	}
	logger.Info("receipt sent", "region", os.Getenv("REGION"))
}

The Go angle ​

  • Constructors are functions. NewT returns *T (and an error when input can be invalid). Prefer useful zero values so many types need no constructor.
  • Return concrete types, accept interfaces is the usual Go advice for constructors; return an interface from a factory whose whole point is to hide which concrete type you get (simplefactory.New, ProviderFor).
  • No inheritance, so Factory Method becomes a value. A func() Channel field or a one-method interface is the hook; tests pass a closure.
  • Functional options are Go's Builder. Pike's option type is "a function that takes one argument, the Foo we are operating on"; Cheney's NewServer(addr, opts...) gives defaults with no arguments and growth without breaking callers. Use a Config struct instead when options are many and mostly data.
  • Global singletons are package variables. They make tests order-dependent (t.Parallel() tests share them) and hide dependencies. Build in main, pass pointers. Use sync.OnceValue only for genuinely process-wide, immutable, lazily built values.
  • Registries are idiomatic for plugins. database/sql, image (image.RegisterFormat), encoding/gob (gob.Register) all use init()-time registration. Keep registration in init() and lookups at startup.
  • DI frameworks are optional. Google Wire's README now says "This project is no longer maintained"; Uber's fx and dig exist; most Go services wire by hand in main or a wire.go-style function.
  • Pools: sync.Pool for buffers and encoders; *sql.DB is already a pool; do not wrap it in your own.

Laravel ​

Before ​

The same smell in a listener: new for concrete channels, env() read at runtime (after config:cache the .env file is no longer loaded, so it only sees system-level variables), and a global static singleton.

php
<?php

namespace App\Listeners;

use App\Events\OrderShipped;
use App\Legacy\Settings;

class SendShipmentNotification
{
    public function handle(OrderShipped $event): void
    {
        $user = $event->order->user;
        $text = "Order {$event->order->id} shipped";

        if ($user->prefers_sms) {
            $sms = new \App\Sms\TwilioClient(env('TWILIO_TOKEN'));          // new + env() at runtime
            $sms->send($user->phone, $text);
        } else {
            $mailer = new \App\Mail\SmtpMailer(Settings::instance()->get('smtp_host')); // global singleton
            $mailer->send($user->email, $text);
        }
    }
}

After ​

The service provider is the composition root: it binds the kit (configuration-driven), uses contextual binding per consumer, registers an HTTP client built with the fluent builder as a singleton, and decorates with extend(). The listener receives NotificationKit in its constructor.

php
<?php

namespace App\Providers;

use App\Http\Controllers\IranCheckoutController;
use App\Http\Controllers\GlobalCheckoutController;
use App\Notifications\Kits\GlobalKit;
use App\Notifications\Kits\IranKit;
use App\Notifications\Kits\NotificationKit;
use App\Services\SmsGatewayClient;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;

// The composition root of a Laravel app: service providers.
class NotificationServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // bind: a new object on every make() / injection (transient).
        $this->app->bind(NotificationKit::class, function (Application $app) {
            // Configuration-driven creation: the deploy picks the family.
            return match (config('notifications.region')) {
                'ir' => new IranKit(config('services.sms_ir.key')),
                default => new GlobalKit(config('services.sms_global.key')),
            };
        });

        // Contextual binding: the same interface, a different family per consumer.
        $this->app->when(IranCheckoutController::class)
            ->needs(NotificationKit::class)
            ->give(fn () => new IranKit(config('services.sms_ir.key')));

        $this->app->when(GlobalCheckoutController::class)
            ->needs(NotificationKit::class)
            ->give(fn () => new GlobalKit(config('services.sms_global.key')));

        // singleton: one HTTP client builder result per process.
        $this->app->singleton(SmsGatewayClient::class, fn () => new SmsGatewayClient(
            Http::baseUrl(config('services.sms_ir.url'))
                ->withToken(config('services.sms_ir.key'))
                ->timeout(3)
                ->connectTimeout(2)
                ->retry(3, 100)
        ));

        // extend: decorate whatever the binding creates (logging, metrics).
        $this->app->extend(NotificationKit::class, function (NotificationKit $kit, Application $app) {
            return $kit; // e.g. new LoggingKit($kit, $app->make('log'))
        });
    }
}

// Resolving: let the container inject; make() belongs in providers, factories
// and framework edges, not in business code (that would be a service locator).
//
//   public function __construct(private NotificationKit $kit) {}   // good
//   $kit = app(NotificationKit::class);                             // locator, avoid in domain code
//   $client = app()->makeWith(SmsGatewayClient::class, ['tenant' => 42]);

The Laravel angle ​

  • The container is your factory. Auto-resolution covers concrete classes; bind interfaces once; prefer constructor injection in listeners, jobs, controllers, actions.
  • Lifetimes matter under Octane. singleton() lives for the worker's lifetime; scoped() for one request or job. Laravel's docs warn against injecting the container or Request into singletons for exactly this reason.
  • Managers are Laravel's driver factories. Cache::store('redis'), Mail::mailer('ses'), Storage::disk('s3'), notification channels: each is Manager::driver() + create{Driver}Driver() + extend() for custom drivers. Write your own manager when you have N interchangeable drivers chosen by config.
  • Notification channels are a built-in factory. via() returns channel names (docs: "Notifications may be sent on the mail, database, broadcast, vonage, and slack channels") or a custom channel class name with a send($notifiable, $notification) method; the framework creates and calls it.
  • Builders everywhere. Query builder, Eloquent builder, Http (PendingRequest), MailMessage, Schema blueprint, model factories: all fluent, all finished by a terminal call (get(), post(), create()).
  • Prototype in Eloquent. $model->replicate() copies attributes into an unsaved model; pass an array to exclude attributes.
  • Testing swaps creation, not code. $this->app->instance() / $this->instance(), Notification::fake(), Http::fake(): each replaces what the container would create.
  • config(), never env(), inside factories. Laravel's configuration docs: once the configuration is cached, "the .env file will not be loaded; therefore, the env function will only return external, system level environment variables."

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Telescoping constructorBuilder / functional options / named argumentsSteps + build(); NewX(req, opts...); PHP 8 named argsReadable, defaults, validation in one placeMore code; mutable builders are not thread-safe
new Concrete scattered in business codeDI + composition rootInject interfaces; build in main/providerTestable, swappableOne more place to look
if ($type == ...) repeated in many placesSimple FactoryOne switch/matchOne edit per new typeEdits the factory (not OCP)
Plugins added by other packagesRegistry / Manager extend()sql.Register, Manager::extend('x', fn)Open for extensionName collisions, init-order surprises
Products that must matchAbstract FactoryOne kit per familyConsistency guaranteedNew product type edits every kit
Global config singleton breaks testsPass config as a valueBuild once in main; instance() in testsParallel tests, explicit depsLonger constructor signatures
Expensive object rarely usedLazy initializationsync.OnceValue, closure binding, PHP 8.4 lazy objectsFaster bootErrors surface at first use
Many short-lived buffersObject poolsync.PoolLess GC pressureReset bugs; only for hot paths
Per-tenant variants of a costly objectPrototype + registryClone base, override fieldsCheap variantsDeep-copy discipline
Test setup is long and fragileTest data builder / Object Mother / model factoriesValid defaults + overridesTests state only what mattersShared mothers can grow into god-objects

Telescoping constructor ​

PHP 8 named arguments solve many cases without a builder: new SmsMessage(to: '+98...', text: 'hi', priority: 1). Reach for a builder when there are invariants across fields (mail needs a subject; SMS ≤ 160 chars) or optional repeated parts (tags, recipients, attachments). In Go, a Config struct with field names is the zero-ceremony option; functional options are better when defaults need logic or you want to add options without touching callers.

Global configuration singleton ​

Replace Settings::instance()->get('x') with a typed config value injected through the constructor. In Laravel, bind the config object with singleton() from config() values; in tests use $this->app->instance() or config(['x' => ...]). In Go, parse configuration once in main into a struct and pass it; never read os.Getenv deep in packages.

Choosing the implementation per environment ​

Use one decision point: ProviderFor(env) in Go's main; bind() with a match (config(...)), or #[Bind(Fake::class, environments: ['local', 'testing'])] in Laravel. The rest of the code never sees the environment.

Choosing ​

SituationRecommendationExtra techniqueReason
One implementation, simple constructionConstructor + DINoneNo pattern needed
Implementation chosen by config or inputSimple Factory at the composition rootReturn interface + errorOne decision point
Reusable algorithm, product varies per subtypeFactory MethodIn Go: interface/func fieldAlgorithm stays closed
Several collaborators must come from one familyAbstract FactoryContextual binding per consumerConsistency
Many optional parameters, invariantsBuilderDirector for common recipesReadable, validated
Configurable long-lived Go objectFunctional optionsDefaults in NewXGrows without breaking callers
Many near-identical costly objectsPrototypeRegistry by nameCheap variants
One per process, statelessContainer singleton / build in mainsync.OnceValue if lazyShared, but injected
One per request/job (Octane, workers)scoped()Never in singletonNo cross-request leaks
Drivers added by pluginsRegistry / Managerextend(), sql.RegisterOpen for extension
Test fixturesModel factories / test data buildersStates, sequencesTests show intent

In architecture: from a single process to a distributed system ​

Creation decisions climb the architecture: in a monolith they are classes and bindings; in a distributed system they are configuration, feature flags and service discovery. The patterns do not change; where they live does.

Monolith: one process, one database ​

All creation happens in one composition root: main.go or the service providers. Everyday example: a Laravel shop binds NotificationKit from config('notifications.region') and injects it into SendShipmentNotification. Production example: the same app under Octane keeps the HTTP client and exchange-rate service as singleton() and the tenant context as scoped(); a code review rule forbids app() inside app/Domain.

Modular monolith and multiple databases ​

Each module owns its composition: a Laravel module has its own service provider; a Go module exposes one constructor such as billing.NewModule(db, clock, kit) and keeps the rest internal/. Other modules receive the module's facade, not its factories. With several databases, a factory per connection name (Laravel's DB::connection('reporting'), Go's one *sql.DB per database built in main) keeps "which database" out of module code. Production example: the billing module binds its own PaymentGatewayFactory with contextual binding so only billing classes get it.

Microservices: creation across a network boundary ​

Each service has its own composition root, and the "factory input" moves from code to deployment configuration: environment variables, mounted secrets, a config service. Abstract Factory becomes "which provider family does this deployment use" (REGION=ir selects the Iran kit), and feature flags select implementations at run time (Laravel Pennant with #[BindWhen], or a flag client in Go). A typical flow:

text
     Step  Component                    Creation decision
1    boot  notification-svc main        read REGION, SMS_PROVIDER, flags from env/config service
2    boot  main                         kit := kitFor(REGION); client := NewClient(url, WithRetries(3))
3    run   order-svc -> Kafka           publishes OrderShipped
4    run   notification-svc consumer    builds message with Builder; kit.SMS().Send(...)
5    run   flag "new-sms-gateway" = 10%  factory returns NewGatewaySMS for 10% of tenants

What does not survive the boundary: a "singleton" is one per process, never one per system. Two replicas have two loggers, two pools, two caches.

Distributed data: replicas, caches and many instances ​

"Exactly one" across a cluster is a coordination problem, not a creational pattern: it needs leader election or a distributed lock (see Leader Election and Distributed Locking). Process-level singletons multiply with replicas: 20 pods × a pool of 25 connections = 500 database connections, which is why connection pooling and PgBouncer exist. Factories that pick read replicas vs the primary (Laravel's read/write connection config, a Go DBRouter with two *sql.DB) are configuration-driven creation at the data layer; caches built lazily per process can hold stale data per replica.

Scaling path: 1×, 10×, 100× ​

LoadCreation concernsWhat changes
1×Readability, testabilityConstructors + DI; one composition root
10×Allocation and connection costProcess singletons for clients and pools; sync.Pool on hot paths; lazy init for rarely used clients; Octane scoped() discipline
100×Many replicas and regionsConfiguration-driven factories, feature flags, per-region kits; connection budgets per pod; no process-level state that assumes it is the only one

Lab: a notification system from Factory Method to Builder ​

Goal: build a notification service in three steps and test each step without real providers.

  1. Factory Method. Service.channelFor(kind) (Go) / NotificationService::channelFor() (PHP) is the hook that maps a kind to a channel; the Send algorithm does not change when a channel is added.
  2. Abstract Factory. Provider creates the mail channel, the SMS channel and the renderer as one family; SandboxProvider and FakeProvider are families for staging and tests.
  3. Builder. NewMessage(kind).To(...).Subject(...).Body(...).Build() validates once: missing recipient, mail without subject, SMS over 160 bytes.
  4. Composition root. ProviderFor(env, rec) is the only simple factory, called once.

Go code and tests:

go
// Package notify is the lab: a notification system that grows from
// Factory Method (step 1) to Abstract Factory (step 2) and Builder (step 3).
package notify

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"sync"
)

// ---- Products ----

// Channel delivers one rendered message to one address.
type Channel interface {
	Deliver(ctx context.Context, to, text string) error
}

// Renderer turns a message into text for one family (locale, branding).
type Renderer interface {
	Render(m Message) string
}

// ---- Step 3: Builder ----

type Message struct {
	Kind    string // "mail" or "sms"
	To      string
	Subject string
	Body    string
}

type MessageBuilder struct {
	m    Message
	errs []error
}

func NewMessage(kind string) *MessageBuilder { return &MessageBuilder{m: Message{Kind: kind}} }

func (b *MessageBuilder) To(to string) *MessageBuilder     { b.m.To = to; return b }
func (b *MessageBuilder) Subject(s string) *MessageBuilder { b.m.Subject = s; return b }
func (b *MessageBuilder) Body(format string, a ...any) *MessageBuilder {
	b.m.Body = fmt.Sprintf(format, a...)
	return b
}

func (b *MessageBuilder) Build() (Message, error) {
	if b.m.To == "" {
		b.errs = append(b.errs, errors.New("missing recipient"))
	}
	if b.m.Kind == "mail" && b.m.Subject == "" {
		b.errs = append(b.errs, errors.New("mail needs a subject"))
	}
	if b.m.Kind == "sms" && len(b.m.Body) > 160 {
		b.errs = append(b.errs, errors.New("sms body over 160 bytes"))
	}
	return b.m, errors.Join(b.errs...)
}

// ---- Step 2: Abstract Factory (a family per environment) ----

type Provider interface {
	Mail() Channel
	SMS() Channel
	Renderer() Renderer
}

// Recorder is a fake channel that remembers what it was asked to send.
type Recorder struct {
	mu   sync.Mutex
	Sent []string
}

func (r *Recorder) Deliver(ctx context.Context, to, text string) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.Sent = append(r.Sent, to+": "+text)
	return nil
}

type plainRenderer struct{ prefix string }

func (p plainRenderer) Render(m Message) string {
	if m.Subject != "" {
		return p.prefix + m.Subject + " | " + m.Body
	}
	return p.prefix + m.Body
}

// FakeProvider: one recorder for both channels, used by tests.
type FakeProvider struct{ Rec *Recorder }

func (f FakeProvider) Mail() Channel      { return f.Rec }
func (f FakeProvider) SMS() Channel       { return f.Rec }
func (f FakeProvider) Renderer() Renderer { return plainRenderer{} }

// SandboxProvider: real wiring, but every message is tagged and goes to a recorder.
type SandboxProvider struct{ Rec *Recorder }

func (s SandboxProvider) Mail() Channel      { return s.Rec }
func (s SandboxProvider) SMS() Channel       { return s.Rec }
func (s SandboxProvider) Renderer() Renderer { return plainRenderer{prefix: "[sandbox] "} }

// ---- Step 1: Factory Method (the Service defers "which channel" to a hook) ----

// Service is the creator; channelFor is its factory method.
type Service struct{ p Provider }

func NewService(p Provider) *Service { return &Service{p: p} }

func (s *Service) channelFor(kind string) (Channel, error) {
	switch kind {
	case "mail":
		return s.p.Mail(), nil
	case "sms":
		return s.p.SMS(), nil
	}
	return nil, fmt.Errorf("notify: unknown channel %q", kind)
}

func (s *Service) Send(ctx context.Context, m Message) error {
	ch, err := s.channelFor(m.Kind)
	if err != nil {
		return err
	}
	return ch.Deliver(ctx, m.To, s.p.Renderer().Render(m))
}

// ProviderFor is the simple factory used once, in main (the composition root).
func ProviderFor(env string, rec *Recorder) (Provider, error) {
	switch strings.ToLower(env) {
	case "test":
		return FakeProvider{Rec: rec}, nil
	case "sandbox", "staging":
		return SandboxProvider{Rec: rec}, nil
	}
	return nil, fmt.Errorf("notify: no provider for env %q", env)
}
go
package notify

import (
	"context"
	"strings"
	"testing"
)

func TestBuilderValidates(t *testing.T) {
	cases := []struct {
		name    string
		b       *MessageBuilder
		wantErr string
	}{
		{"ok mail", NewMessage("mail").To("a@x.io").Subject("Hi").Body("order %d", 7), ""},
		{"no recipient", NewMessage("sms").Body("x"), "missing recipient"},
		{"mail without subject", NewMessage("mail").To("a@x.io").Body("x"), "needs a subject"},
		{"sms too long", NewMessage("sms").To("+98").Body("%s", strings.Repeat("a", 161)), "over 160"},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			_, err := tc.b.Build()
			if tc.wantErr == "" && err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if tc.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tc.wantErr)) {
				t.Fatalf("want error containing %q, got %v", tc.wantErr, err)
			}
		})
	}
}

func TestServiceUsesTheWholeFamily(t *testing.T) {
	rec := &Recorder{}
	p, err := ProviderFor("sandbox", rec)
	if err != nil {
		t.Fatal(err)
	}
	msg, _ := NewMessage("sms").To("+989120000000").Body("code %d", 4821).Build()
	if err := NewService(p).Send(context.Background(), msg); err != nil {
		t.Fatal(err)
	}
	if got := rec.Sent[0]; got != "+989120000000: [sandbox] code 4821" {
		t.Fatalf("got %q", got)
	}
}

func TestUnknownChannelAndEnv(t *testing.T) {
	if _, err := ProviderFor("prod-typo", nil); err == nil {
		t.Fatal("want error for unknown env")
	}
	s := NewService(FakeProvider{Rec: &Recorder{}})
	if err := s.Send(context.Background(), Message{Kind: "fax", To: "x"}); err == nil {
		t.Fatal("want error for unknown channel")
	}
}

Run it:

bash
cd docs/snippets/design/creational-patterns/go
gofmt -l .        # no output
go vet ./...      # no output
go test ./...
# ok   academy/creational-patterns/lab/notify   0.4s
# ok   academy/creational-patterns/prototype    0.4s
# ok   academy/creational-patterns/singleton    0.4s
go test -race ./singleton/   # RacyInstance is not called by tests; call it from two goroutines to see the race report

Laravel version (classes in one file for reading) and its test, which swaps the abstract factory through the container with $this->app->instance():

php
<?php

// Lab: one file for reading; in an app each class gets its own PSR-4 file.

namespace App\Notify;

use InvalidArgumentException;

// ---- Products ----

interface Channel
{
    public function deliver(string $to, string $text): void;
}

interface Renderer
{
    public function render(Message $m): string;
}

// ---- Step 3: Builder ----

final class Message
{
    public function __construct(
        public readonly string $kind,
        public readonly string $to,
        public readonly string $subject,
        public readonly string $body,
    ) {}
}

final class MessageBuilder
{
    private string $to = '';
    private string $subject = '';
    private string $body = '';

    private function __construct(private string $kind) {}

    public static function mail(): self
    {
        return new self('mail');
    }

    public static function sms(): self
    {
        return new self('sms');
    }

    public function to(string $to): self
    {
        $this->to = $to;

        return $this;
    }

    public function subject(string $subject): self
    {
        $this->subject = $subject;

        return $this;
    }

    public function body(string $body): self
    {
        $this->body = $body;

        return $this;
    }

    public function build(): Message
    {
        $errors = [];
        if ($this->to === '') {
            $errors[] = 'missing recipient';
        }
        if ($this->kind === 'mail' && $this->subject === '') {
            $errors[] = 'mail needs a subject';
        }
        if ($this->kind === 'sms' && strlen($this->body) > 160) {
            $errors[] = 'sms body over 160 bytes';
        }
        if ($errors !== []) {
            throw new InvalidArgumentException(implode('; ', $errors));
        }

        return new Message($this->kind, $this->to, $this->subject, $this->body);
    }
}

// ---- Step 2: Abstract Factory ----

interface Provider
{
    public function mail(): Channel;

    public function sms(): Channel;

    public function renderer(): Renderer;
}

final class Recorder implements Channel
{
    /** @var list<string> */
    public array $sent = [];

    public function deliver(string $to, string $text): void
    {
        $this->sent[] = "{$to}: {$text}";
    }
}

final class PlainRenderer implements Renderer
{
    public function __construct(private string $prefix = '') {}

    public function render(Message $m): string
    {
        return $this->prefix.($m->subject !== '' ? "{$m->subject} | {$m->body}" : $m->body);
    }
}

final class SandboxProvider implements Provider
{
    public function __construct(private Recorder $recorder) {}

    public function mail(): Channel
    {
        return $this->recorder;
    }

    public function sms(): Channel
    {
        return $this->recorder;
    }

    public function renderer(): Renderer
    {
        return new PlainRenderer('[sandbox] ');
    }
}

// ---- Step 1: Factory Method ----

class NotificationService
{
    public function __construct(private Provider $provider) {}

    // The factory method: subclasses may override to add channels.
    protected function channelFor(string $kind): Channel
    {
        return match ($kind) {
            'mail' => $this->provider->mail(),
            'sms' => $this->provider->sms(),
            default => throw new InvalidArgumentException("Unknown channel [{$kind}]."),
        };
    }

    public function send(Message $m): void
    {
        $this->channelFor($m->kind)->deliver($m->to, $this->provider->renderer()->render($m));
    }
}

// Wiring (in a service provider):
//   $this->app->singleton(Recorder::class);
//   $this->app->bind(Provider::class, fn ($app) => match (config('notify.env')) {
//       'sandbox', 'testing' => new SandboxProvider($app->make(Recorder::class)),
//       default => $app->make(LiveProvider::class),
//   });
php
<?php

namespace Tests\Unit;

use App\Notify\MessageBuilder;
use App\Notify\NotificationService;
use App\Notify\Provider;
use App\Notify\Recorder;
use App\Notify\SandboxProvider;
use InvalidArgumentException;
use Tests\TestCase;

class NotifyTest extends TestCase
{
    public function test_builder_rejects_mail_without_subject(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('mail needs a subject');

        MessageBuilder::mail()->to('a@x.io')->body('hi')->build();
    }

    public function test_service_uses_the_bound_family(): void
    {
        $recorder = new Recorder();
        // Swap the abstract factory in the container for this test only.
        $this->app->instance(Provider::class, new SandboxProvider($recorder));

        $service = $this->app->make(NotificationService::class);
        $service->send(MessageBuilder::sms()->to('+989120000000')->body('code 4821')->build());

        $this->assertSame(['+989120000000: [sandbox] code 4821'], $recorder->sent);
    }

    public function test_unknown_channel_fails_loudly(): void
    {
        $this->expectException(InvalidArgumentException::class);

        $service = new NotificationService(new SandboxProvider(new Recorder()));
        $service->send(new \App\Notify\Message('fax', 'x', '', 'hi'));
    }
}

Experiments:

  1. Add a push channel. Count the files you edit (expected: the Provider interface, each provider, channelFor). That is the Abstract Factory cost of a new product type.
  2. Add a LiveProvider family. Count the files you edit (expected: one new type and one line in ProviderFor). That is the benefit of a new family.
  3. Replace ProviderFor with a registry (map[string]func(*Recorder) Provider) and register providers in init(). Compare with the database/sql driver model.
  4. Make Recorder a package-level singleton and run the Go tests with -count=2 -shuffle=on. Watch TestServiceUsesTheWholeFamily read the previous run's messages; then go back to injection.
  5. In Laravel, register Recorder with singleton() and run a two-request test under Octane semantics ($this->app->forgetScopedInstances() does not reset singletons); switch to scoped() and compare.

Common misconceptions ​

BeliefReality
"Every new should go through a factory"Only creation with logic needs a factory; constructors plus DI are the default
"Singleton is the way to share one instance"Sharing is a lifetime decision for main or the container; the GoF Singleton adds global access, which is the harmful part
"sync.Once makes my singleton testable"It makes it thread-safe; it is still global state shared by every test
"A static create() is the Factory Method pattern"That is a static factory method / named constructor; the GoF pattern is a hook a subclass or plug-in overrides
"An abstract simple factory is an Abstract Factory"Abstract Factory creates a family of several product types
"Builder means method chaining"Chaining is syntax; the pattern separates construction from a finished, validated product
"clone copies everything"PHP clone and Go *t are shallow; nested objects, maps and slices must be copied by hand
"Laravel facades make every class a service locator"Only if business code pulls dependencies from them; constructor injection keeps a composition root
"PHP singletons are dangerous because of threads"Under PHP-FPM a static lives one request; the real danger is long-running workers (Octane, queues) leaking state between requests
"A singleton in a microservice is one per system"It is one per process; 20 replicas mean 20 instances
"Lazy initialization is always better"It moves cost and failures to the first request; eager creation fails fast at deploy
"Object pools save memory everywhere"They help only for costly or very frequent allocations and add reset/use-after-return bugs

Cheat sheet ​

TopicRemember
DefaultConstructor + dependency injection; factories only when creation has logic
Composition rootOne place (main, service providers) builds the graph; nothing below calls new for collaborators
SingletonLifetime, not a static; Go: build in main or sync.OnceValue; Laravel: singleton() / scoped()
Octane / workersscoped() for per-request state; never inject Request or the container into a singleton
Simple FactoryOne switch/match, returns an interface, errors on unknown kinds
Factory MethodFixed algorithm + creation hook; in Go a func or interface field
Abstract FactorySeveral product types from one family; new family = cheap, new product type = expensive
BuilderSteps + one validating build(); Go functional options for configurable constructors
PrototypeCopy + tweak; deep-copy maps, slices, nested objects; Eloquent replicate()
RegistryName → constructor, filled at startup (sql.Register, Manager::extend())
Service locatorPulling dependencies inside methods; hides them; avoid in domain code
Lazy initsync.OnceValue, closure bindings, PHP 8.4 lazy objects; costs first-request latency
Object poolsync.Pool for buffers; *sql.DB is already a pool
TestsModel factories with states, test data builders, instance() / fakes through constructors
MicroservicesFactory input becomes config, secrets and feature flags; singletons are per process

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What two problems does the GoF Singleton solve at once, and which one causes the trouble? Important ​

Answer

Answer: It guarantees one instance and provides global access to it. The global access is the problem: hidden dependencies, shared state between tests and (in long-running PHP) between requests. See Singleton.

2 — Why is sync.Once correct while a nil check is not? Must-know ​

Answer

Answer: Two goroutines can both see nil and both initialise (a data race). once.Do runs f once and, per the Go memory model, the return from f synchronizes before every return from once.Do. See Thread safety.

3 — Your Laravel app moves to Octane and users start seeing each other's tenant names. Which binding is wrong and what replaces it? Must-know ​

Answer

Answer: A per-request object (tenant context) bound with singleton() lives for the whole worker. Bind it with scoped() (or #[Scoped]) so it is flushed per request or job. See Container lifetimes.

4 — What is the difference between a Simple Factory and the Factory Method pattern? Must-know ​

Answer

Answer: A Simple Factory is one function with a conditional choosing the class. Factory Method is a hook inside a creator's algorithm that subclasses (or plugged-in values) override to choose the product. See Simple Factory and Factory Method.

5 — Name the cheap change and the expensive change for an Abstract Factory. Good to know ​

Answer

Answer: A new family (a new concrete factory) is cheap. A new product type (a new method on the factory interface) is expensive: every concrete factory changes. See the lab, experiments 1 and 2.

6 — How does Go express Builder idiomatically, and when would you use a Config struct instead? Important ​

Answer

Answer: Functional options (NewClient(url, WithTimeout(...), WithRetries(...))) for configurable constructors, or a step builder with Build() (T, error) for validated values. A Config struct is simpler when options are many plain data fields with no logic. See Builder.

7 — Why does clone in PHP or c := *t in Go often break the Prototype pattern? Important ​

Answer

Answer: Both are shallow: nested objects (PHP) and maps, slices and pointers (Go) are shared with the original, so changes leak back. Deep-copy in __clone() or Clone(). See Prototype.

8 — Is app(Mailer::class) inside a domain service a problem? What about inside a service provider? Important ​

Answer

Answer: Inside a domain service it is the service-locator anti-pattern: a hidden dependency that fails at run time. Inside a provider (the composition root) it is normal wiring. See Service locator.

9 — What happens if two Go packages call sql.Register with the same name, and what if you forget to import a driver? Good to know ​

Answer

Answer: Register panics with sql: Register called twice for driver <name>; Open returns sql: unknown driver "<name>" (forgotten import?). See Error messages.

10 — In a system with 30 pods, how many instances does a "singleton" HTTP client have, and how do you get exactly one active instance cluster-wide? Must-know ​

Answer

Answer: Thirty, one per process. Cluster-wide "exactly one" needs coordination (leader election or a distributed lock), not a creational pattern. See Distributed data.

11 — When is lazy initialization the wrong choice? Important ​

Answer

Answer: When failing fast at deploy matters (bad credentials should fail the health check), when first-request latency matters, or when the object is always used anyway. See Lazy initialization.

Glossary ​

TermMeaning
Creational patternA pattern about how, when and which objects are created
Gang of Four (GoF)Gamma, Helm, Johnson, Vlissides, authors of Design Patterns (1994)
SingletonOne instance plus a global access point (GoF)
Simple FactoryOne creation function with a conditional (Head First; not GoF)
Factory MethodA creation hook that subclasses or plug-ins override (GoF)
Abstract FactoryAn interface creating a family of related products (GoF)
BuilderStep-by-step construction with a final build() (GoF)
DirectorOptional object that runs builder steps in a fixed order
PrototypeCreating objects by copying a configured instance (GoF)
Prototype registryName → prototype map that returns clones
Product / concrete productThe interface created / its implementation
Creator / concrete creatorThe class declaring / overriding the factory method
Product familyProducts that must be used together (one kit)
Static factory method / named constructorA static method or function with a meaningful name that returns an instance
Telescoping constructorMany overloaded or optional constructor parameters
Fluent interfaceMethod chaining that returns the builder (return $this)
Functional optionsGo idiom: variadic func(*T) arguments that configure a new value
Test data builderA builder with valid defaults for tests
Object MotherA class of named, ready-made example objects for tests (Fowler)
Eloquent model factoryLaravel class with definition(), states, make() and create()
Shallow copyCopy of the top-level fields; nested references are shared
Deep copyCopy that also duplicates nested objects, maps and slices
__clone()PHP magic method run on the copy after clone
replicate()Eloquent method returning an unsaved copy of a model
Lazy initializationCreating on first use
Lazy ghost / lazy proxyPHP 8.4 lazy-object strategies: initialize in place / delegate to a real instance
sync.Once, sync.OnceValueGo primitives that run an initializer exactly once, thread-safely
Double-checked lockingJava/C# lazy-singleton idiom that is broken without proper memory barriers
Object poolA set of reusable instances lent out and returned (sync.Pool)
RegistryWell-known object to find common objects and services (Fowler)
MultitonOne instance per key
Manager (Laravel)Illuminate\Support\Manager: driver registry + factory with extend()
Dependency injection (DI)Giving an object its dependencies instead of letting it create them
Composition rootThe single place where the object graph is built (Seemann)
DI containerLibrary that automates wiring and lifetimes (Laravel container, Spring, .NET)
Service locatorPulling dependencies from a global registry inside business code (anti-pattern per Seemann)
PSR-11PHP standard container interface (Psr\Container\ContainerInterface)
Lifetime: transient / scoped / singletonNew each time / one per request or job / one per process
Contextual bindingLaravel when()->needs()->give(): per-consumer implementation
Binding attributesLaravel #[Bind], #[BindWhen], #[Singleton], #[Scoped]
Feature flagRuntime switch that can change which implementation a factory returns (e.g. Laravel Pennant)
Configuration-driven creationFactories whose choice comes from config, env, tenant data or flags
Laravel OctaneLong-running Laravel server; singletons live across requests
Google WireGo compile-time DI code generator; README says it is no longer maintained

References ​

Built by Morteza Negahi