{"id":"6b08bd3480884893657cc960","slug":"factory-method","title":"Factory Method – let the subclass decide what gets created","summary":"Factory Method separates the algorithm that uses an object from the decision about which exact object is created. A ticket booking example in C#, TypeScript, Java, Go and Python.","servedLang":"en","availableLangs":["pl","en"],"topics":["factory-method","abstract-factory","template-method"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","creational","factory-method","polymorphism"],"level":"intermediate","kind":"article","access":"public","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":11,"stats":{"views":6,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:13:56.030Z","updatedAt":"2026-11-27T13:05:24.185Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"The Factory Method design pattern in practice – the problem, a UML diagram, code in C#, TypeScript, Java, Go and Python, pros, cons, how it differs from Abstract Factory, and interview questions.","wordCount":2072,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Code that creates something and code that uses it often live in the same method – until the day the product needs a second variant. "},{"type":"text","text":"Factory Method","marks":[{"type":"bold"}]},{"type":"text","text":" moves the decision \"which class do I instantiate\" into a separate, overridable method, so the rest of the algorithm never learns about concrete types."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A base class (the "},{"type":"text","text":"creator","marks":[{"type":"italic"}]},{"type":"text","text":") has a method that returns a product through an interface – subclasses decide which one exactly."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The algorithm that uses the product stays in one place and does not change when a new variant arrives."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"It is the simplest of the GoF creational patterns and the foundation of "},{"type":"text","text":"Abstract Factory","marks":[{"type":"link","attrs":{"href":"/en/topics/abstract-factory"}}]},{"type":"text","text":"."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"1994","label":"year \"Design Patterns\" was published","hint":"Gamma, Helm, Johnson, Vlissides"},{"value":"5","label":"creational patterns in the GoF catalog","hint":"this is the first one on our path"},{"value":"2","label":"class hierarchies","hint":"creators and products grow side by side"}]}},{"type":"heading","attrs":{"level":2,"id":"the-problem-a-booking-that-knows-too-much"},"content":[{"type":"text","text":"The problem: a booking that knows too much"}]},{"type":"paragraph","content":[{"type":"text","text":"You are building a ticket sales service. At first there are only concerts: a customer books a seat, the system issues a ticket with a seat number and emails it. Then festivals arrive (a multi-day wristband with no numbered seats), and soon webinars (a streaming link). The easiest path looks like this:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"booking-service.ts"},"content":[{"type":"text","text":"class BookingService {\n  book(kind: \"concert\" | \"festival\" | \"webinar\", holder: string): Ticket {\n    let ticket: Ticket;\n    if (kind === \"concert\") ticket = new SeatTicket(holder, this.pickSeat());\n    else if (kind === \"festival\") ticket = new WristbandPass(holder, 3);\n    else ticket = new StreamAccess(holder, this.generateLink());\n    this.mailer.send(holder, ticket.describe()); // the part that never changes\n    return ticket;\n  }\n}"}]},{"type":"paragraph","content":[{"type":"text","text":"It works, but every new kind of event means editing the same method, adding another "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":" branch and retesting the delivery logic nobody actually touched. The class breaks the open–closed principle from "},{"type":"text","text":"SOLID","marks":[{"type":"link","attrs":{"href":"/en/topics/solid"}}]},{"type":"text","text":": it is open for modification instead of extension."}]},{"type":"heading","attrs":{"level":2,"id":"the-solution-extract-the-decision-into-a-method"},"content":[{"type":"text","text":"The solution: extract the decision into a method"}]},{"type":"paragraph","content":[{"type":"text","text":"The base class keeps what is shared – validation, delivery, logging – and the bare "},{"type":"text","text":"new","marks":[{"type":"code"}]},{"type":"text","text":" goes behind an abstract "},{"type":"text","text":"createTicket()","marks":[{"type":"code"}]},{"type":"text","text":" method. Every kind of event becomes a subclass that overrides just that one method. The "},{"type":"text","text":"book()","marks":[{"type":"code"}]},{"type":"text","text":" algorithm talks only to the "},{"type":"text","text":"Ticket","marks":[{"type":"code"}]},{"type":"text","text":" interface."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  direction LR\n  class BookingFlow {\n    <<abstract>>\n    +book(holder) Ticket\n    #createTicket(holder)* Ticket\n  }\n  class ConcertBooking {\n    #createTicket(holder) Ticket\n  }\n  class FestivalBooking {\n    #createTicket(holder) Ticket\n  }\n  class Ticket {\n    <<interface>>\n    +describe() string\n  }\n  BookingFlow <|-- ConcertBooking\n  BookingFlow <|-- FestivalBooking\n  Ticket <|.. SeatTicket\n  Ticket <|.. WristbandPass\n  BookingFlow ..> Ticket : uses\n  ConcertBooking ..> SeatTicket : creates\n  FestivalBooking ..> WristbandPass : creates","caption":"Factory Method structure in the ticket booking example"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Role"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"In the example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Responsibility"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Product"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Ticket","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the common interface of everything that can be created"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Concrete product"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"SeatTicket","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"WristbandPass","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"concrete ticket variants"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Creator"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"BookingFlow","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the algorithm that uses the product + the factory method declaration"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Concrete creator"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ConcertBooking","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"FestivalBooking","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"decides which product to create"}]}]}]}]},{"type":"pullQuote","attrs":{"text":"Define an interface for creating an object, but let subclasses decide which class to instantiate.","author":"Gamma","role":"Helm, Johnson, Vlissides","source":"Design Patterns (1994)"}},{"type":"paragraph","content":[{"type":"text","text":"Notice that the creator is not a \"factory\" in the everyday sense – its main job is booking, and creating the ticket is just one step. That is what separates Factory Method from a class that does nothing but build objects."}]},{"type":"heading","attrs":{"level":2,"id":"implementation-in-five-languages"},"content":[{"type":"text","text":"Implementation in five languages"}]},{"type":"paragraph","content":[{"type":"text","text":"In C#, TypeScript, Java and Python we use classic inheritance. Go has no subclasses, so an injected "},{"type":"text","text":"TicketMaker","marks":[{"type":"code"}]},{"type":"text","text":" function plays the role of the factory method – the same idea expressed through composition instead of a hierarchy."}]},{"type":"codeGroup","attrs":{"title":"BookingFlow.createTicket()"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Tickets.cs"},"content":[{"type":"text","text":"var flows = new BookingFlow[] { new ConcertBooking(), new FestivalBooking() };\nforeach (var flow in flows)\n    flow.Book(\"Ola\");\n\npublic interface ITicket\n{\n    string Describe();\n}\n\npublic sealed record SeatTicket(string Holder, string Seat) : ITicket\n{\n    public string Describe() => $\"Seat {Seat} for {Holder}\";\n}\n\npublic sealed record WristbandPass(string Holder, int Days) : ITicket\n{\n    public string Describe() => $\"{Days}-day wristband for {Holder}\";\n}\n\n// Creator: the booking algorithm is fixed, the kind of ticket is not.\npublic abstract class BookingFlow\n{\n    public ITicket Book(string holder)\n    {\n        ArgumentException.ThrowIfNullOrWhiteSpace(holder);\n        var ticket = CreateTicket(holder); // the factory method\n        Console.WriteLine($\"Sending: {ticket.Describe()}\");\n        return ticket;\n    }\n\n    protected abstract ITicket CreateTicket(string holder);\n}\n\npublic sealed class ConcertBooking : BookingFlow\n{\n    protected override ITicket CreateTicket(string holder) => new SeatTicket(holder, \"B-12\");\n}\n\npublic sealed class FestivalBooking : BookingFlow\n{\n    protected override ITicket CreateTicket(string holder) => new WristbandPass(holder, 3);\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"tickets.ts"},"content":[{"type":"text","text":"interface Ticket {\n  describe(): string;\n}\n\nclass SeatTicket implements Ticket {\n  constructor(private readonly holder: string, private readonly seat: string) {}\n  describe(): string {\n    return `Seat ${this.seat} for ${this.holder}`;\n  }\n}\n\nclass WristbandPass implements Ticket {\n  constructor(private readonly holder: string, private readonly days: number) {}\n  describe(): string {\n    return `${this.days}-day wristband for ${this.holder}`;\n  }\n}\n\n// Creator: the booking algorithm is fixed, the kind of ticket is not.\nabstract class BookingFlow {\n  book(holder: string): Ticket {\n    if (!holder.trim()) throw new Error(\"Holder is required\");\n    const ticket = this.createTicket(holder); // the factory method\n    console.log(`Sending: ${ticket.describe()}`);\n    return ticket;\n  }\n\n  protected abstract createTicket(holder: string): Ticket;\n}\n\nclass ConcertBooking extends BookingFlow {\n  protected createTicket(holder: string): Ticket {\n    return new SeatTicket(holder, \"B-12\");\n  }\n}\n\nclass FestivalBooking extends BookingFlow {\n  protected createTicket(holder: string): Ticket {\n    return new WristbandPass(holder, 3);\n  }\n}\n\nfor (const flow of [new ConcertBooking(), new FestivalBooking()]) flow.book(\"Ola\");"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Tickets.java"},"content":[{"type":"text","text":"import java.util.List;\n\ninterface Ticket {\n    String describe();\n}\n\nrecord SeatTicket(String holder, String seat) implements Ticket {\n    public String describe() { return \"Seat \" + seat + \" for \" + holder; }\n}\n\nrecord WristbandPass(String holder, int days) implements Ticket {\n    public String describe() { return days + \"-day wristband for \" + holder; }\n}\n\n// Creator: the booking algorithm is fixed, the kind of ticket is not.\nabstract class BookingFlow {\n    public final Ticket book(String holder) {\n        if (holder == null || holder.isBlank()) throw new IllegalArgumentException(\"Holder is required\");\n        Ticket ticket = createTicket(holder); // the factory method\n        System.out.println(\"Sending: \" + ticket.describe());\n        return ticket;\n    }\n\n    protected abstract Ticket createTicket(String holder);\n}\n\nclass ConcertBooking extends BookingFlow {\n    @Override\n    protected Ticket createTicket(String holder) { return new SeatTicket(holder, \"B-12\"); }\n}\n\nclass FestivalBooking extends BookingFlow {\n    @Override\n    protected Ticket createTicket(String holder) { return new WristbandPass(holder, 3); }\n}\n\npublic class Tickets {\n    public static void main(String[] args) {\n        List<BookingFlow> flows = List.of(new ConcertBooking(), new FestivalBooking());\n        flows.forEach(flow -> flow.book(\"Ola\"));\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"tickets.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Ticket interface {\n\tDescribe() string\n}\n\ntype SeatTicket struct{ Holder, Seat string }\n\nfunc (t SeatTicket) Describe() string { return fmt.Sprintf(\"Seat %s for %s\", t.Seat, t.Holder) }\n\ntype WristbandPass struct {\n\tHolder string\n\tDays   int\n}\n\nfunc (p WristbandPass) Describe() string {\n\treturn fmt.Sprintf(\"%d-day wristband for %s\", p.Days, p.Holder)\n}\n\n// Go has no inheritance: the factory method is a function value injected into the flow.\ntype TicketMaker func(holder string) Ticket\n\ntype BookingFlow struct{ makeTicket TicketMaker }\n\nfunc (f BookingFlow) Book(holder string) (Ticket, error) {\n\tif holder == \"\" {\n\t\treturn nil, errors.New(\"holder is required\")\n\t}\n\tt := f.makeTicket(holder)\n\tfmt.Println(\"Sending:\", t.Describe())\n\treturn t, nil\n}\n\nfunc main() {\n\tconcert := BookingFlow{makeTicket: func(h string) Ticket { return SeatTicket{Holder: h, Seat: \"B-12\"} }}\n\tfestival := BookingFlow{makeTicket: func(h string) Ticket { return WristbandPass{Holder: h, Days: 3} }}\n\tfor _, flow := range []BookingFlow{concert, festival} {\n\t\tif _, err := flow.Book(\"Ola\"); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"tickets.py"},"content":[{"type":"text","text":"from abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\n\nclass Ticket(Protocol):\n    def describe(self) -> str: ...\n\n\n@dataclass(frozen=True)\nclass SeatTicket:\n    holder: str\n    seat: str\n\n    def describe(self) -> str:\n        return f\"Seat {self.seat} for {self.holder}\"\n\n\n@dataclass(frozen=True)\nclass WristbandPass:\n    holder: str\n    days: int\n\n    def describe(self) -> str:\n        return f\"{self.days}-day wristband for {self.holder}\"\n\n\nclass BookingFlow(ABC):\n    \"\"\"Creator: the booking algorithm is fixed, the kind of ticket is not.\"\"\"\n\n    def book(self, holder: str) -> Ticket:\n        if not holder.strip():\n            raise ValueError(\"holder is required\")\n        ticket = self.create_ticket(holder)  # the factory method\n        print(f\"Sending: {ticket.describe()}\")\n        return ticket\n\n    @abstractmethod\n    def create_ticket(self, holder: str) -> Ticket: ...\n\n\nclass ConcertBooking(BookingFlow):\n    def create_ticket(self, holder: str) -> Ticket:\n        return SeatTicket(holder, seat=\"B-12\")\n\n\nclass FestivalBooking(BookingFlow):\n    def create_ticket(self, holder: str) -> Ticket:\n        return WristbandPass(holder, days=3)\n\n\nif __name__ == \"__main__\":\n    for flow in (ConcertBooking(), FestivalBooking()):\n        flow.book(\"Ola\")"}]}]},{"type":"callout","attrs":{"variant":"tip","title":"A variant without inheritance"},"content":[{"type":"paragraph","content":[{"type":"text","text":"In languages with first-class functions (TypeScript, Python, Go, and for a long time C# and Java too) the factory method is often replaced by a parameter: "},{"type":"text","text":"new BookingFlow(holder => new SeatTicket(holder, \"B-12\"))","marks":[{"type":"code"}]},{"type":"text","text":". Less ceremony, same division of roles."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-by-step"},"content":[{"type":"text","text":"Step by step"}]},{"type":"timeline","attrs":{"items":[{"date":"Step 1","title":"Find new inside the algorithm","text":"Look for places where choosing a class is mixed with logic you want to keep unchanged."},{"date":"Step 2","title":"Extract the product interface","text":"All variants must satisfy a common contract that the algorithm relies on (describe())."},{"date":"Step 3","title":"Add the factory method","text":"Declare createTicket() in the base class – abstract or with a sensible default implementation."},{"date":"Step 4","title":"Move the variants into subclasses","text":"Each if branch becomes a subclass that overrides only the factory method."},{"date":"Step 5","title":"Delete the conditionals","text":"Choosing the subclass moves to the edge of the system – configuration, a DI container or a single composition root."}]}},{"type":"heading","attrs":{"level":2,"id":"when-to-use-it-and-when-not-to"},"content":[{"type":"text","text":"When to use it and when not to"}]},{"type":"prosCons","attrs":{"pros":["a new product variant is a new class, not an edit of working code","the algorithm depends on an abstraction, so it is easy to test with a fake product","one place for complex creation logic (defaults, validation)","a natural extension point for frameworks and libraries"],"cons":["every variant needs its own creator subclass","the creator and product hierarchies grow in parallel","with two variants and no prospect of a third, it is just overhead"],"prosTitle":"Pros","consTitle":"Cons"}},{"type":"paragraph","content":[{"type":"text","text":"The pattern pays off when you have a stable algorithm and a growing list of product variants, or when you write a library whose users should plug in their own objects. Skip it if there is a single variant and \"maybe one day there will be a second\" – "},{"type":"text","text":"YAGNI","marks":[{"type":"link","attrs":{"href":"/en/topics/yagni"}}]},{"type":"text","text":" wins."}]},{"type":"callout","attrs":{"variant":"warning","title":"A common mistake"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A static "},{"type":"text","text":"Ticket.create(kind)","marks":[{"type":"code"}]},{"type":"text","text":" method with a "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" inside is a "},{"type":"text","text":"simple factory","marks":[{"type":"italic"}]},{"type":"text","text":", not Factory Method. It can be handy, but it offers no extension point: a new variant still requires editing the "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":". Factory Method relies on polymorphism – overriding a method or injecting a function."}]}]},{"type":"heading","attrs":{"level":2,"id":"factory-method-and-testing"},"content":[{"type":"text","text":"Factory Method and testing"}]},{"type":"paragraph","content":[{"type":"text","text":"For a tester this is one of the friendliest patterns. Since the "},{"type":"text","text":"book()","marks":[{"type":"code"}]},{"type":"text","text":" algorithm receives a ticket only through "},{"type":"text","text":"createTicket()","marks":[{"type":"code"}]},{"type":"text","text":", a test needs nothing more than a tiny subclass – or, in the functional variant, a lambda – that returns a fake ticket with a predictable description. You then check the booking logic alone: validation, delivery, error handling, without picking random seats or generating streaming links. It works the other way round, too: each concrete creator has so little code that its test boils down to a single assertion, \""},{"type":"text","text":"ConcertBooking","marks":[{"type":"code"}]},{"type":"text","text":" issues a "},{"type":"text","text":"SeatTicket","marks":[{"type":"code"}]},{"type":"text","text":"\". If you are writing tests for code with a giant "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" on types, extracting a factory method is often the cheapest first refactoring step."}]},{"type":"heading","attrs":{"level":2,"id":"related-patterns"},"content":[{"type":"text","text":"Related patterns"}]},{"type":"paragraph","content":[{"type":"text","text":"Factory Method is often a step inside a "},{"type":"text","text":"Template Method","marks":[{"type":"link","attrs":{"href":"/en/topics/template-method"}}]},{"type":"text","text":" – just like "},{"type":"text","text":"book()","marks":[{"type":"code"}]},{"type":"text","text":" is the template here and "},{"type":"text","text":"createTicket()","marks":[{"type":"code"}]},{"type":"text","text":" its replaceable step. When you need to create a "},{"type":"text","text":"family","marks":[{"type":"bold"}]},{"type":"text","text":" of matching objects, several factory methods gather into one object – that is "},{"type":"text","text":"Abstract Factory","marks":[{"type":"link","attrs":{"href":"/en/topics/abstract-factory"}}]},{"type":"text","text":". If you would rather copy a ready-made instance than build one from scratch, look at "},{"type":"text","text":"Prototype","marks":[{"type":"link","attrs":{"href":"/en/topics/prototype"}}]},{"type":"text","text":"."}]},{"type":"linkCard","attrs":{"url":"/en/topics/abstract-factory","title":"Abstract Factory","description":"Whole families of products instead of one","kind":"topic","ref":"abstract-factory"}},{"type":"linkCard","attrs":{"url":"/en/topics/template-method","title":"Template Method","description":"An algorithm skeleton with replaceable steps","kind":"topic","ref":"template-method"}},{"type":"linkCard","attrs":{"url":"/en/topics/prototype","title":"Prototype","description":"Creating by copying a ready-made instance","kind":"topic","ref":"prototype"}},{"type":"heading","attrs":{"level":2,"id":"in-practice-where-you-already-use-it"},"content":[{"type":"text","text":"In practice: where you already use it"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":".NET","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"ILoggerProvider.CreateLogger(categoryName)","marks":[{"type":"code"}]},{"type":"text","text":": each provider (console, debug, third-party libraries) returns its own "},{"type":"text","text":"ILogger","marks":[{"type":"code"}]},{"type":"text","text":" implementation, while "},{"type":"text","text":"LoggerFactory","marks":[{"type":"code"}]},{"type":"text","text":" works only with the interface."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Java","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"Iterable.iterator()","marks":[{"type":"code"}]},{"type":"text","text":": every collection creates its own iterator, and the for-each loop knows only "},{"type":"text","text":"Iterator","marks":[{"type":"code"}]},{"type":"text","text":". In Spring, "},{"type":"text","text":"FactoryBean<T>.getObject()","marks":[{"type":"code"}]},{"type":"text","text":" plays a similar role."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Go","marks":[{"type":"bold"}]},{"type":"text","text":" – the "},{"type":"text","text":"database/sql/driver.Driver","marks":[{"type":"code"}]},{"type":"text","text":" interface with "},{"type":"text","text":"Open(name string) (Conn, error)","marks":[{"type":"code"}]},{"type":"text","text":": the "},{"type":"text","text":"database/sql","marks":[{"type":"code"}]},{"type":"text","text":" package uses connections, and each driver decides which exact connection it creates."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Python","marks":[{"type":"bold"}]},{"type":"text","text":" – in Django class-based views, "},{"type":"text","text":"get_form_class()","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"get_queryset()","marks":[{"type":"code"}]},{"type":"text","text":" are factory methods you override in a subclass; "},{"type":"text","text":"__iter__","marks":[{"type":"code"}]},{"type":"text","text":" is a method that creates an iterator as well."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Node/TypeScript","marks":[{"type":"bold"}]},{"type":"text","text":" – in NestJS a provider with "},{"type":"text","text":"useFactory","marks":[{"type":"code"}]},{"type":"text","text":" moves the creation decision into a function; this is the \"factory method as a parameter\" variant."}]}]}]},{"type":"resourceRef","attrs":{"resourceId":"6b0854ad1a40d7e6c24c8eae"}},{"type":"heading","attrs":{"level":2,"id":"quick-check"},"content":[{"type":"text","text":"Quick check"}]},{"type":"quiz","attrs":{"question":"Which piece of code is a Factory Method in the GoF sense?","multiple":false,"options":[{"text":"A static Ticket.create(kind) method with a switch on the ticket kind","correct":false,"explanation":"That is a simple factory – a new variant still requires changing existing code."},{"text":"The abstract createTicket() in BookingFlow, overridden by ConcertBooking","correct":true,"explanation":"Yes – the subclass decides the product class, and the book() algorithm knows only the interface."},{"text":"The SeatTicket(holder, seat) constructor with parameter validation","correct":false,"explanation":"A constructor always creates the same type – there is no polymorphism here."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Interview question: how does Factory Method differ from Abstract Factory?"}]},{"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"Factory Method is "},{"type":"text","text":"a single method","marks":[{"type":"bold"}]},{"type":"text","text":" in a class whose main job is something else (booking, in our case); you pick the variant through inheritance or by injecting a function. Abstract Factory is "},{"type":"text","text":"a separate object","marks":[{"type":"bold"}]},{"type":"text","text":" with several methods that create products of one family (e.g. a charge, a refund and a webhook verifier of the same provider); you pick the variant by passing a different factory object. Abstract factories are frequently implemented with factory methods."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"summary"},"content":[{"type":"text","text":"Summary"}]},{"type":"paragraph","content":[{"type":"text","text":"Factory Method is a way to stop an algorithm from guessing which object to create. You extract that decision into one overridable method and gain a place where the system grows by adding classes rather than by appending "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":" branches. The next step on the path – "},{"type":"text","text":"Abstract Factory","marks":[{"type":"link","attrs":{"href":"/en/articles/abstract-factory"}}]},{"type":"text","text":" – shows what to do when objects have to match each other in whole families."}]}]},"toc":[{"id":"the-problem-a-booking-that-knows-too-much","text":"The problem: a booking that knows too much","level":2,"locked":false},{"id":"the-solution-extract-the-decision-into-a-method","text":"The solution: extract the decision into a method","level":2,"locked":false},{"id":"implementation-in-five-languages","text":"Implementation in five languages","level":2,"locked":false},{"id":"step-by-step","text":"Step by step","level":2,"locked":false},{"id":"when-to-use-it-and-when-not-to","text":"When to use it and when not to","level":2,"locked":false},{"id":"factory-method-and-testing","text":"Factory Method and testing","level":2,"locked":false},{"id":"related-patterns","text":"Related patterns","level":2,"locked":false},{"id":"in-practice-where-you-already-use-it","text":"In practice: where you already use it","level":2,"locked":false},{"id":"quick-check","text":"Quick check","level":2,"locked":false},{"id":"summary","text":"Summary","level":2,"locked":false}],"locked":false,"paywall":null,"previewRatio":0.3,"totalBlocks":38,"visibleBlocks":38,"resources":[{"id":"6b0857a53c96f2d34d0b321d","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=EcFVTgRHJLM","embedUrl":"https://www.youtube-nocookie.com/embed/EcFVTgRHJLM","title":"Factory Method Pattern – Design Patterns (ep 4)","description":"","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/EcFVTgRHJLM/hqdefault.jpg","durationSec":null,"lang":"en","topics":["factory-method"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:37.643Z","updatedAt":"2026-11-26T16:00:37.643Z"},{"id":"6b0857c33c96f2d34d0b4658","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL6030812W","embedUrl":null,"title":"Design Patterns: Elements of Reusable Object-Oriented Software","description":"","author":"Erich Gamma, John Vlissides, Richard Helm, Ralph Johnson","thumbnailUrl":"https://covers.openlibrary.org/b/id/6601119-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["general"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"1995-01-01T00:00:00.000Z","popularity":71,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c33c96f2d34d0b4666","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL16942701W","embedUrl":null,"title":"Head First design patterns","description":"","author":"Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates","thumbnailUrl":"https://covers.openlibrary.org/b/id/388950-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["java"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2004-01-01T00:00:00.000Z","popularity":62,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c83c96f2d34d0b49f2","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=IlmOokWznyI","embedUrl":"https://www.youtube-nocookie.com/embed/IlmOokWznyI","title":"Design Patterns in Dynamic Languages | Code Walks 016","description":"Do dynamically typed languages really need design patterns? 02:43 The short version of the argument 03:04 Strategy pattern 05:25 Factory pattern GEAR USED ► MIC: RØDE SmartLav+ http://amzn.to/21nVI3o ► CAMERA: iPhone 6 http://amzn.to/1UeVCXv Original upload date: Jun 24, 2016","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/IlmOokWznyI/hqdefault.jpg","durationSec":null,"lang":"en","topics":["strategy"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2016-07-16T09:26:14.000Z","popularity":59,"verifiedAt":"2026-11-26T10:57:18.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857be3c96f2d34d0b41dd","type":"article","provider":"web","url":"https://refactoring.guru/design-patterns/factory-method","embedUrl":null,"title":"Factory Method","description":"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.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"en","topics":["factory-method"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":80,"verifiedAt":"2026-11-26T11:25:59.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"}],"challenges":[{"id":"6b0857af5a2625e44ecaad0a","slug":"notification-factory","title":"Notification factory","summary":"Implement Factory Method: every notification service decides which channel (e-mail, SMS, push) it creates.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":null,"status":"published","difficulty":"easy","topics":["factory-method"],"techs":["typescript","javascript"],"tags":["factory-method","notifications","creational"],"languages":["typescript","javascript"],"questionCount":null,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":1,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.675Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-creational","title":"GoF creational patterns","items":[{"slug":"factory-method","title":"Factory Method – let the subclass decide what gets created","current":true},{"slug":"abstract-factory","title":"Abstract Factory – whole families of objects that fit together","current":false},{"slug":"builder","title":"Builder – complex objects step by step","current":false},{"slug":"prototype","title":"Prototype – a new object as a copy of a ready-made template","current":false},{"slug":"singleton","title":"Singleton – one instance, and the reasons to hand it to a DI container","current":false}]}],"prev":null,"next":{"slug":"abstract-factory","title":"Abstract Factory – whole families of objects that fit together"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}