Factory Method Pattern
Keep a shared workflow while subclasses decide which concrete object it creates and uses.
· Last updated: 2026-11-07 · 9 min read
Overview
Consider an export job that formats the same data as CSV or as a JSON string. A writer is the object responsible for this conversion. Write a job class per format and those same steps get copied once per format. If only the writer changes, the export jobs can share their workflow rather than repeat it for each format.
Factory Method keeps the shared workflow in a base class and lets subclasses implement the method that creates the writer used by that workflow. The base class uses only the returned product's interface, so a subclass can change which writer is created.
UML
Watch the direction of the call. ExportJob.Run() obtains an IWriter through Create(); CsvJob and JsonJob implement Create(), and Run() stays in the base class and is shared as is.
History
GoF cataloged Factory Method as a creational pattern in Design Patterns in 1994. It delegates a concrete creation choice to subclasses.1
Letting a base framework class own the overall workflow while deferring object instantiation to an overridable hook—often called a Virtual Constructor—was highlighted by Ralph Johnson and Brian Foote in their 1988 paper on reusable framework design.2 Because an application framework knows *when* a document or view must be created long before it knows *which* concrete subclass the application developer will write, it leaves instantiation to a virtual factory method.
Why use it?
A new writer can be attached without copying the shared sequence of steps. Because the creation point stands apart, the code shows which object is actually chosen. Adding a format touches one creation method and nothing else.
Start with the near neighbour that is easy to confuse with it. A static function that returns an object is often called a factory function; the mechanism here is overriding a creation method through inheritance. And when the writer is already injected from outside, the hierarchy may be unnecessary.
Example
The roles split in two here. CsvJob creates the CSV writer, and the shared ExportJob.Run() uses it.
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(new CsvJob().Run());
interface IWriter { string Write(string value); }
sealed class CsvWriter : IWriter
{
public string Write(string value) => "\"" + value.Replace("\"", "\"\"") + "\"";
}
sealed class JsonWriter : IWriter
{
public string Write(string value) => System.Text.Json.JsonSerializer.Serialize(new { value });
}
// The shared workflow uses the contract returned by the creation method.
abstract class ExportJob
{
protected abstract IWriter Create();
public string Run() => Create().Write("hello");
}
// Change only product selection and inherit the execution sequence.
sealed class CsvJob : ExportJob
{
protected override IWriter Create() => new CsvWriter();
}
sealed class JsonJob : ExportJob
{
protected override IWriter Create() => new JsonWriter();
}
"hello"Run() never constructs CsvWriter. Choosing a job implementation is separate from the shared workflow, so a new format is one more job class.
An extended example
Add a JSON job and run both jobs through the same ExportJob type. The shared workflow holds while formats multiply. The quotation marks in the string are left to the JSON serializer instead of being inserted by hand.
using System;
using System.Collections.Generic;
using System.Linq;
foreach (ExportJob job in new ExportJob[] { new CsvJob(), new JsonJob() })
Console.WriteLine(job.Run());
interface IWriter { string Write(string value); }
sealed class CsvWriter : IWriter
{
public string Write(string value) => "\"" + value.Replace("\"", "\"\"") + "\"";
}
sealed class JsonWriter : IWriter
{
public string Write(string value) => System.Text.Json.JsonSerializer.Serialize(new { value });
}
// The shared workflow uses the contract returned by the creation method.
abstract class ExportJob
{
protected abstract IWriter Create();
public string Run() => Create().Write("hello");
}
// Change only product selection and inherit the execution sequence.
sealed class CsvJob : ExportJob
{
protected override IWriter Create() => new CsvWriter();
}
sealed class JsonJob : ExportJob
{
protected override IWriter Create() => new JsonWriter();
}
"hello"
{"value":"hello"}Run() stays the same while Create() returns different products. Only the output changes, not the order of steps. A Factory Method can also be one of the customizable steps inside a Template Method.
TypeScript example
Move the same design to TypeScript and the boundary holds. ExportJob owns when to create and use a writer. CsvJob and JsonJob only choose which writer to construct, so another format does not need another copy of run().
interface IWriter { write(value: string): string; }
class CsvWriter implements IWriter {
write(value: string): string { return '"' + value.replaceAll('"', '""') + '"'; }
}
class JsonWriter implements IWriter {
write(value: string): string { return JSON.stringify({ value }); }
}
// The shared workflow uses the contract returned by the creation method.
abstract class ExportJob {
protected abstract create(): IWriter;
run(): string { return this.create().write("hello"); }
}
// Change only product selection and inherit the execution sequence.
class CsvJob extends ExportJob {
protected override create(): IWriter { return new CsvWriter(); }
}
class JsonJob extends ExportJob {
protected override create(): IWriter { return new JsonWriter(); }
}
for (const job of [new CsvJob(), new JsonJob()]) console.log(job.run());"hello"
{"value":"hello"}Create and Write become create and write in the TypeScript version. These writers return CSV and JSON strings rather than writing files.
Keeping the product type with FactoryMethod<T>
One more step generalizes the product type itself. T in FactoryMethod<T> is the product type used by the common workflow. The base calls CreateProduct(), and a subclass chooses which object to construct. A type argument does not select a concrete product by itself; the overridden creation method still makes that choice.
The common workflow needs products that can supply printable text. The C# constraint where T : IProduct and the TypeScript constraint T extends Product put that requirement into the type, so the caller never receives object or any and has to cast it back.
C#
using System;
var creator = new TextFactory();
TextProduct product = creator.CreateProduct();
Console.WriteLine(creator.RunFactory());
Console.WriteLine(product.Text);
// TYPES
interface IProduct { string Render(); }
abstract class FactoryMethod<T> where T : IProduct
{
public abstract T CreateProduct();
// The common workflow delegates concrete construction.
public string RunFactory() => "factory:" + CreateProduct().Render();
}
sealed class TextProduct : IProduct
{
public string Text => "hello";
public string Render() => Text;
}
sealed class TextFactory : FactoryMethod<TextProduct>
{
public override TextProduct CreateProduct() => new();
}factory:hello
helloTypeScript
interface Product { render(): string; }
abstract class FactoryMethod<T extends Product> {
abstract createProduct(): T;
// Apply the same workflow to the product supplied by a subclass.
runFactory(): string { return "factory:" + this.createProduct().render(); }
}
class TextProduct implements Product {
readonly text = "hello";
render(): string { return this.text; }
}
class TextFactory extends FactoryMethod<TextProduct> {
override createProduct(): TextProduct { return new TextProduct(); }
}
const creator = new TextFactory();
const product: TextProduct = creator.createProduct();
console.log(creator.runFactory());
console.log(product.text);factory:hello
helloOne distinction is still worth drawing. A general-purpose factory that takes a creation function as an argument is not a Factory Method overridden by a subclass. This example keeps the latter relationship and generalizes the product type.
The official references describe the type-parameter syntax and library contracts.3
Static factory methods, Simple Factory, and when to prefer injection
Three distinct idioms share the word "factory" in everyday code, and mixing them up obscures design discussions. First, a static factory method such as TimeSpan.FromSeconds(30) or DateTime.Parse() is simply a named static constructor on a single class—no polymorphism or subclassing is involved. Second, a Simple Factory centralizes a switch statement that instantiates concrete classes based on a key. Third, the GoF Factory Method pattern lets subclasses override a virtual creation method to select the concrete product. In this example, a Template Method Pattern workflow (Run()) calls the creation step (Create()).
When should you keep that inheritance hierarchy versus replacing it with Composition and Dependency injection? If subclasses customize several interrelated protected hooks alongside object creation, Factory Method fits naturally. If, however, CsvJob and JsonJob exist solely to contain a one-line return new CsvWriter(), creating a new subclass per product is unnecessary ceremony: passing an IWriter or a Func<IWriter> delegate directly into ExportJob's constructor eliminates the subclass hierarchy altogether.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Creational patterns, Factory Method. ↩
- Ralph E. Johnson and Brian Foote, "Designing Reusable Classes," Journal of Object-Oriented Programming 1(2), 1988, pp. 22–35. Paper PDF. ↩
- C# generics; TypeScript generics ↩