Conceptcore
Creational pattern
Also called creational patterns, creational design pattern, object creation pattern, class creational pattern, object creational pattern.
A creational pattern is a design pattern for the creation of objects. It hides which concrete classes a program uses and how their instances are created and combined.
- Applies to
- core-languages
Idea
Most code creates objects with a constructor: Square(2) or new Square(2). The call names a concrete class. That is fine until the class must change: a different class for each platform, a copy of an object that a user has set up, one shared object in place of many, or an object with ten optional parts. Then each place that names the class must change.
A creational pattern moves the knowledge of the class, and of how to build it, out of the code that uses the object. Wikipedia gives the two main aspects: a creational pattern hides which concrete classes the system uses, and it hides how instances of these classes are created and combined.1
import copy
class Circle:
def __init__(self, size):
self.size = size
class Square:
def __init__(self, size):
self.size = size
# A constructor: the caller names the class.
print("constructor:", type(Square(2)).__name__)
# A factory: the caller names a kind, and one place picks the class.
KINDS = {"circle": Circle, "square": Square}
def make(kind, size):
return KINDS[kind](size)
print("factory:", [type(make(k, 2)).__name__ for k in ("circle", "square")])
# A prototype: the caller copies an object that it already has.
template = Square(3)
clone = copy.copy(template)
print("prototype:", type(clone).__name__, clone.size, clone is template)
# One shared instance: every caller gets the same object.
_shared = Square(1)
def shared():
return _shared
print("singleton:", shared() is shared())
constructor: Square
factory: ['Circle', 'Square']
prototype: Square 3 False
singleton: True
The constructor call ties the caller to Square. The factory lets the caller say what it wants, and one function decides the class. The prototype creates an object from an existing object, so the caller does not need to know the class. The shared instance decides how many objects exist. Each of these is a small form of a creational pattern.
How it works
What the patterns share. A creational pattern aims to separate a system from how its objects are created, composed and represented, and it gives the system flexibility in what is created, who creates it, how and when.1 The code that uses an object depends on an interface, and the code that knows the concrete class is in one place. Design Patterns states the link to its principle program to an interface, not an implementation: the creational patterns give ways to create concrete objects while the rest of the system is written in terms of interfaces.2
Class and object creational patterns. Design Patterns classifies its patterns by purpose (creational, structural, behavioral) and by scope (class or object).2 A class creational pattern defers object creation to subclasses. An object creational pattern defers part of the creation to another object.1 Factory Method is the only class creational pattern of the book. Abstract Factory, Builder, Prototype and Singleton are object creational.2
| Question | Pattern | Who decides |
|---|---|---|
| Which class? | Factory Method pattern | a subclass overrides a creation method |
| Which family of classes? | Abstract Factory pattern | a factory object that the client is given |
| How is a complex object put together? | Builder pattern | a builder object, step by step |
| Which class, from an example? | Prototype pattern | an existing object, which is copied |
| How many instances? | Singleton pattern | the class, which keeps one instance |
Other named patterns answer the same questions. Wikipedia also lists lazy initialization, which delays the creation of an object until the first time it is needed, and the object pool, which recycles objects that are no longer in use.1 Dependency injection moves the creation out of the class: the class accepts the objects it requires from an injector, and does not create them.1 A Static factory method replaces a constructor with a named method, and a Multiton keeps one instance for each key.
When a constructor is enough. A pattern is worth its cost only when the creation must vary. If the caller knows the class, the class has a few required parameters, and no other class will take its place, a constructor call is the clearest code. Effective Java gives a middle step: a static factory method has a name, does not need to create a new object on each call, and can return an object of a subtype.3 Its next items recommend a builder when a constructor has many parameters, and a private constructor or an enum type for a singleton.3
Languages change the patterns. Peter Norvig studied the 23 patterns of Design Patterns and found that 16 of them have a qualitatively simpler implementation in Lisp or Dylan than in C++, for at least some uses of each pattern.4 For the creational patterns the main reason is first-class types. When classes are objects at run time, a variable can hold a class, and the class itself serves as the factory, so there is no need for a parallel hierarchy of factories and products.4 He also noted that a language that can dispatch on constant values needs no singletons.4
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Idiom | A function allocates a struct and returns a pointer to it, often to an opaque type, as fopen returns a FILE pointer; a struct of function pointers lets a factory pick the behaviour. Alternative: A static variable inside a function for a single shared instance. |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Native | An object declaration is a singleton in the language, initialized on first access in a thread-safe way; named and default arguments replace most builders, and a companion object holds factory functions; no example is executed here because the test image has no kotlinc. Alternative: Data classes with copy for changed copies. |
| SQL | Does not apply | INSERT creates rows, and default values and sequences fill columns, but there are no objects or classes to create. |
| Bash | Does not apply | The shell has strings and arrays, not objects; a function can print a value or set a variable. |
| PowerShell | Idiom | A class can have static factory methods, a hashtable converts to a pscustomobject, and .NET objects that support it have a Clone method; no example is executed here because the test image has no pwsh. Alternative: A function that returns a pscustomobject. |
| HTML | Does not apply | The author writes each element; the template element holds markup that a script can copy into the document. |
| CSS | Does not apply | Style rules create no objects. |
| Regular expressions | Does not apply | A pattern creates no objects. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | classes are values and act as factories; copy.copy and copy.deepcopy; keyword arguments with defaults; a module is a singleton |
| JavaScript | idiom | factory functions that return object literals; Object.create with a prototype; classes are values; option objects |
| TypeScript | idiom | the forms of JavaScript with types; constructor types such as new () => T; Partial<T> for options |
| Java | idiom | static factory methods such as List.of; constructor references as Supplier; an enum for a singleton; builders |
| Kotlin | native | an object declaration is a singleton; named and default arguments; companion objects for factories |
| C# | idiom | object initializers and init properties; with for records; Func<T> factories; Lazy<T> |
| Go | idiom | a useful zero value; composite literals; constructor functions named NewT; sync.OnceValue |
| Rust | idiom | new by convention; Default and struct update syntax; Clone; builder types; OnceLock |
| C | idiom | functions that allocate and return a pointer to an opaque struct; a table of function pointers |
| C++ | idiom | std::make_unique and std::make_shared; copy constructors and a virtual clone; a function-local static |
| Bash | n/a | the shell has no objects; a function can return a name or print a value |
| PowerShell | idiom | classes with static methods; [pscustomobject] from a hashtable; .Clone() on .NET objects |
| SQL | n/a | INSERT creates rows, and default values and sequences fill columns, but there are no objects to create |
| Regex | n/a | a pattern creates no objects |
| HTML | n/a | the author writes each element; <template> holds markup that a script can copy |
| CSS | n/a | style rules create no objects |
The patterns matter most in languages where a constructor call must name a class at compile time and where classes are not values: Java, C#, C++. In Python and JavaScript, a class is a value, so a factory is often a dictionary or a parameter. Python's FAQ notes that there is only one instance of each module, so a module is also the basis for the singleton pattern.5 JavaScript has prototypes in the language: Object.create creates a new object with an existing object as its prototype.6 Kotlin has a singleton in the language: an object declaration creates one, and its initialization is thread-safe and done on first access.7 Named and default arguments, in Python, Kotlin and C#, remove most of the need for a builder. C# object initializers let a caller assign accessible fields or properties of an object when it creates the object.8
Go and Rust have no constructors in the language. Effective Go advises to design types so that the zero value can be used without further initialization, and names the constructor of the type Ring NewRing, or New when the package exports only that type.9 A composite literal creates a new instance each time it is evaluated.9 Rust uses an associated function named new, struct update syntax to create an instance from most of the values of another instance,10 and the Rust API Guidelines recommend a builder type for data structures that need many inputs or optional configuration.11
The example files show these forms. Python and JavaScript use classes as values and copy objects. TypeScript types a constructor parameter and an options object. Java uses List.of, ArrayList::new and an enum singleton. C# uses an object initializer, with and Lazy<T>. C++ uses std::make_unique, a virtual clone and a function-local static. Go uses the zero value of bytes.Buffer, a composite literal and NewRequest. Rust uses new, Default, struct update syntax and OnceLock.
import copy
import importlib
import json
from dataclasses import dataclass, replace
class Circle:
def __init__(self, size):
self.size = size
class Square:
def __init__(self, size):
self.size = size
# A class is a value, so a dict of classes is a factory.
kinds = {"circle": Circle, "square": Square}
shape = kinds["square"](2)
print("factory:", type(shape).__name__, shape.size)
# A copy of an object that you have is a prototype.
template = Square(3)
clone = copy.copy(template)
print("prototype:", type(clone).__name__, clone.size, clone is template)
# Keyword arguments with defaults do the work of a builder.
@dataclass(frozen=True)
class Request:
url: str
method: str = "GET"
timeout: float = 30.0
retries: int = 0
r = Request("https://example.com/", retries=2)
print("builder:", r)
print("changed copy:", replace(r, method="POST"))
# A module is created once, so an object in a module is a singleton.
print("singleton:", importlib.import_module("json") is json)
factory: Square 2
prototype: Square 3 False
builder: Request(url='https://example.com/', method='GET', timeout=30.0, retries=2)
changed copy: Request(url='https://example.com/', method='POST', timeout=30.0, retries=2)
singleton: True
- Verdict: idiom. Python makes most creational patterns small. A class is a value, so a table of classes is a factory.
copy.copycopies an object, keyword arguments with defaults replace most builders, anddataclasses.replacemakes a changed copy. A module is imported once, so a module-level object is a singleton.
#include <iostream>
#include <memory>
#include <string>
struct Shape {
virtual ~Shape() = default;
virtual std::unique_ptr<Shape> clone() const = 0; // the prototype operation
virtual std::string name() const = 0;
int size = 1;
};
struct Square : Shape {
std::unique_ptr<Shape> clone() const override { return std::make_unique<Square>(*this); }
std::string name() const override { return "Square"; }
};
struct Registry {
int lookups = 0;
};
Registry& registry() {
static Registry instance; // made once, on the first call
return instance;
}
struct Request {
std::string url;
std::string method = "GET";
int retries = 0;
};
int main() {
// std::make_unique is a factory function that forwards its arguments.
std::unique_ptr<Shape> shape = std::make_unique<Square>();
shape->size = 3;
// A virtual clone copies an object through a pointer to its base class.
std::unique_ptr<Shape> copy = shape->clone();
std::cout << "prototype: " << copy->name() << " " << copy->size << " "
<< std::boolalpha << (copy != shape) << "\n";
++registry().lookups;
++registry().lookups;
std::cout << "singleton: " << registry().lookups << " lookups on one instance\n";
// Designated initializers and default member values replace a small builder.
Request r{.url = "https://example.com/", .retries = 2};
std::cout << "initializer: " << r.url << " " << r.method << " " << r.retries << "\n";
}
prototype: Square 3 true
singleton: 2 lookups on one instance
initializer: https://example.com/ GET 2
- Verdict: idiom.
std::make_uniqueandstd::make_sharedare factory functions. A copy constructor copies an object of a known class, and a virtualclonecopies through a base pointer, which is the Prototype pattern. A function-localstaticis a lazy singleton. Designated initializers with default member values replace a builder for a plain struct.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
public class Main {
// An enum with one constant is a singleton.
enum Registry {
INSTANCE;
int lookups;
}
record Request(String url, String method, int retries) {
Request withMethod(String newMethod) {
return new Request(url, newMethod, retries);
}
}
public static void main(String[] args) {
// A static factory method: List.of returns an unmodifiable list.
List<String> names = List.of("ann", "bob");
try {
names.add("cy");
} catch (UnsupportedOperationException e) {
System.out.println("static factory: the list from List.of is unmodifiable");
}
// A constructor reference is a factory object.
Supplier<List<String>> factory = ArrayList::new;
List<String> a = factory.get();
List<String> b = factory.get();
System.out.println("factory: " + a.getClass().getSimpleName() + ", a new object each time: " + (a != b));
Registry.INSTANCE.lookups++;
Registry.INSTANCE.lookups++;
System.out.println("singleton: " + Registry.INSTANCE.lookups + " lookups on one instance");
// A record copies with one change through a method that you write.
Request r = new Request("https://example.com/", "GET", 2);
System.out.println("changed copy: " + r.withMethod("POST"));
}
}
static factory: the list from List.of is unmodifiable
factory: ArrayList, a new object each time: true
singleton: 2 lookups on one instance
changed copy: Request[url=https://example.com/, method=POST, retries=2]
- Verdict: idiom. Java writes the patterns in classes. The standard library uses static factory methods such as
List.of, a constructor reference such asArrayList::newis a factory object of typeSupplier, and an enum with one constant is the safe form of a singleton. A class with many optional fields usually gets a builder, because Java has no named or default arguments.
using System;
using System.Collections.Generic;
// An object initializer sets properties when the object is created.
var options = new Options { Url = "https://example.com/", Retries = 2 };
Console.WriteLine($"initializer: {options.Url} {options.Method} {options.Retries}");
// A with expression makes a copy of a record with some changes.
var get = new Request("https://example.com/", "GET");
var post = get with { Method = "POST" };
Console.WriteLine($"changed copy: {post}");
// A Func<T> is a factory object.
Func<List<int>> factory = () => new List<int>();
Console.WriteLine($"factory: a new object each time: {!ReferenceEquals(factory(), factory())}");
// Lazy<T> in a static field gives a thread-safe singleton that is made on first use.
Console.WriteLine($"singleton: {ReferenceEquals(Clock.Instance, Clock.Instance)}, created {Clock.Created} time");
sealed class Options
{
public string Url { get; init; } = "";
public string Method { get; init; } = "GET";
public int Retries { get; init; }
}
record Request(string Url, string Method);
sealed class Clock
{
static readonly Lazy<Clock> instance = new(() => new Clock());
public static int Created;
Clock() => Created++;
public static Clock Instance => instance.Value;
}
initializer: https://example.com/ GET 2
changed copy: Request { Url = https://example.com/, Method = POST }
factory: a new object each time: True
singleton: True, created 1 time
- Verdict: idiom. Object initializers with
initproperties replace most builders, and awithexpression copies a record with changes. A delegate such asFunc<T>is a factory, andLazy<T>gives a lazy singleton.
// A factory function returns a new object; no class is needed.
function makePoint(x, y) {
return {
x,
y,
norm() {
return Math.hypot(this.x, this.y);
},
};
}
console.log("factory function:", makePoint(3, 4).norm());
// Object.create makes a new object that has an existing object as its prototype.
const base = {
greet() {
return `hello from ${this.name}`;
},
};
const ann = Object.create(base);
ann.name = "ann";
console.log("prototype:", ann.greet(), Object.getPrototypeOf(ann) === base);
// A class is a value, so code can receive the class that it must create.
class Circle {
constructor(size) {
this.size = size;
}
}
class Square {
constructor(size) {
this.size = size;
}
}
const create = (Kind, size) => new Kind(size);
console.log("class as value:", [Circle, Square].map((K) => create(K, 2).constructor.name).join(" "));
// Defaults and the spread syntax do the work of a builder.
const defaults = { method: "GET", timeout: 30, retries: 0 };
const request = { url: "https://example.com/", ...defaults, retries: 2 };
console.log("builder:", JSON.stringify(request));
factory function: 5
prototype: hello from ann true
class as value: Circle Square
builder: {"url":"https://example.com/","method":"GET","timeout":30,"retries":2}
- Verdict: idiom. An object literal in a function is a factory, and
Object.createmakes an object from a prototype, which is the model of objects in JavaScript. Classes are values, so the code that creates can take the class as an argument. An options object with defaults and the spread syntax replaces most builders.
interface Shape {
area(): number;
}
class Circle implements Shape {
r: number;
constructor(r: number) {
this.r = r;
}
area(): number {
return Math.round(Math.PI * this.r ** 2 * 100) / 100;
}
}
class Square implements Shape {
s: number;
constructor(s: number) {
this.s = s;
}
area(): number {
return this.s ** 2;
}
}
// A constructor type lets a function create an object of the class it gets.
type ShapeClass = new (size: number) => Shape;
function create(Kind: ShapeClass, size: number): Shape {
return new Kind(size);
}
console.log("factory:", create(Circle, 1).area(), create(Square, 2).area());
// Defaults and a Partial type do the work of a builder.
interface Options {
method: string;
timeout: number;
retries: number;
}
const defaults: Options = { method: "GET", timeout: 30, retries: 0 };
function request(url: string, options: Partial<Options> = {}) {
return { url, ...defaults, ...options };
}
console.log("builder:", JSON.stringify(request("https://example.com/", { retries: 2 })));
// structuredClone makes a deep copy of plain data: a prototype for data.
const template = { tags: ["a"], size: 1 };
const copy = structuredClone(template);
copy.tags.push("b");
console.log("prototype:", template.tags.join(","), "|", copy.tags.join(","));
factory: 3.14 4
builder: {"url":"https://example.com/","method":"GET","timeout":30,"retries":2}
prototype: a | a,b
- Verdict: idiom. The forms are those of JavaScript, with types. A constructor type such as
new (size: number) => Shapelets a factory take a class as an argument and still check it.Partial<Options>types an options object with defaults, which replaces most builders.structuredClonemakes a deep copy of plain data.
package main
import (
"bytes"
"fmt"
"sync"
)
type Request struct {
URL string
Method string
Retries int
}
// NewRequest is a constructor function: it fills in the defaults.
func NewRequest(url string) *Request {
return &Request{URL: url, Method: "GET"}
}
// config is made once, on the first call.
var config = sync.OnceValue(func() string {
fmt.Println("loading config")
return "prod"
})
func main() {
// The zero value is ready to use, so no constructor is needed.
var buf bytes.Buffer
buf.WriteString("ready to use")
fmt.Println("zero value:", buf.String())
// A composite literal names the fields.
r := Request{URL: "https://example.com/", Retries: 2}
fmt.Printf("literal: %+v\n", r)
fmt.Printf("constructor: %+v\n", *NewRequest("https://example.com/"))
// Assignment copies a struct, so a value is its own prototype.
c := r
c.Method = "POST"
fmt.Printf("copy: %q %q\n", r.Method, c.Method)
fmt.Println("singleton:", config(), config())
}
zero value: ready to use
literal: {URL:https://example.com/ Method: Retries:2}
constructor: {URL:https://example.com/ Method:GET Retries:0}
copy: "" "POST"
loading config
singleton: prod prod
- Verdict: idiom. Go has no constructors. A type whose zero value is ready to use needs no creation code, a composite literal names the fields, and a function named
NewTis the constructor when the defaults matter. Assignment copies a struct value.sync.OnceValuemakes a value once.
use std::sync::OnceLock;
#[derive(Debug, Clone, Default)]
struct Request {
url: String,
method: String,
retries: u32,
}
impl Request {
// By convention, `new` is the constructor; it is an ordinary function.
fn new(url: &str) -> Self {
Request { url: url.to_string(), method: "GET".to_string(), ..Default::default() }
}
}
fn config() -> &'static str {
static CONFIG: OnceLock<String> = OnceLock::new();
CONFIG.get_or_init(|| {
println!("loading config");
"prod".to_string()
})
}
fn main() {
let r = Request::new("https://example.com/");
println!("new: {r:?}");
// Struct update syntax copies the other fields from another value.
let r2 = Request { retries: 2, ..r.clone() };
println!("update: {r2:?}");
println!("default: {:?}", Request::default());
// Clone is the prototype operation.
let mut c = r2.clone();
c.method = "POST".to_string();
println!("clone: {} {}", r2.method, c.method);
println!("singleton: {} {}", config(), std::ptr::eq(config(), config()));
}
new: Request { url: "https://example.com/", method: "GET", retries: 0 }
update: Request { url: "https://example.com/", method: "GET", retries: 2 }
default: Request { url: "", method: "", retries: 0 }
clone: GET POST
loading config
singleton: prod true
- Verdict: idiom. Rust has no constructors in the language.
newis a convention for an associated function,Defaultgives default values, and struct update syntax fills the other fields from another value.Cloneis the prototype operation. A builder type is common for values with many options, andOnceLockin astaticis a lazy singleton.
Variations and related ideas
- Factory functions and factory objects. A function that returns a new object is the simplest factory. An object with a creation method can be passed to other code, so the caller decides what they create.
- Dependency injection. A container or the main function creates the objects and passes them in. The classes then need no creational pattern of their own.
- Copy and update. Records in C# and Java, data classes in Python and Kotlin, and struct update syntax in Rust make a changed copy of a value. For immutable data this does the work of a prototype.
- Object lifetime patterns. Object pools, lazy initialization and multitons decide when an object is made and how long it lives, more than which class it has.
Pitfalls
- A pattern where a constructor is enough. A factory for one class, or an abstract factory with one family, adds names and indirection and gives nothing in return.
- A singleton as hidden global state. Code that calls a singleton has a dependency that its signature does not show, and tests cannot replace it easily. Pass the object in when you can.
- A shallow copy as a prototype. A shallow copy constructs a new compound object and inserts references to the objects found in the original.12 A clone that shares a list with its prototype changes the prototype when the list changes. Use a deep copy, or make the shared parts immutable.
- A builder that allows an incomplete object. If the builder does not check the required fields in
build, the program fails later and far from the cause. - Creation that is not thread-safe. A lazy singleton or a registry that checks and then creates can create two objects when two threads race.
Cost
A creational pattern adds an indirection: a call to a factory in place of a constructor, and often a virtual call or a lookup in a table. The run-time cost is small, but the cost in reading is real. A reader must find the factory to learn which class a call creates. In Rust, a factory that picks the type at run time returns a trait object such as Box<dyn Trait>, which is allocated on the heap and calls its methods through dynamic dispatch. A pool or a singleton trades memory for speed, because its objects stay alive.
History
Design Patterns, by Gamma, Helm, Johnson and Vlissides, appeared in 1994. It classified 23 patterns by purpose and scope, and its creational group has five patterns: Abstract Factory, Builder, Factory Method, Prototype and Singleton.2 Factory Method is a class pattern, and the other four are object patterns.2
Peter Norvig first presented Design Patterns in Dynamic Programming on 5 May 1996. He argued that 16 of the 23 patterns are either invisible or simpler in Dylan or Lisp, and that first-class types make Abstract Factory and Factory Method invisible or simpler.4 Later lists of creational patterns add patterns from other sources, such as dependency injection, lazy initialization and the object pool.1 Effective Java opens its chapter on creating and destroying objects with static factory methods, builders and singletons.3
References
- Creational pattern, Wikipedia, Introduction; Usage; Examples
- Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 1, Organizing the Catalog (Table 1.1) and Program to an interface; Chapter 3, Creational Patterns, introduction and discussion
- Joshua Bloch, Effective Java, third edition, Addison-Wesley, 2018, Chapter 2, Items 1 to 3
- Peter Norvig, Design Patterns in Dynamic Programming, Object World, 1996, slides 8 to 11 and 48
- Programming FAQ, Python 3.14 documentation, How do I share global variables across modules?
- Object.create(), MDN Web Docs, Introduction
- Object declarations and expressions, Kotlin documentation, Introduction; Object declarations
- Object and Collection Initializers, C# programming guide, Object initializers
- Effective Go, Package names; Allocation with new; Constructors and composite literals
- Defining and Instantiating Structs, The Rust Programming Language, Creating Instances with Struct Update Syntax
- Type safety, Rust API Guidelines, Builders enable construction of complex values (C-BUILDER)
- copy, The Python Standard Library, Python 3.14, Introduction; Interface summary
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag ZFKCA8 Edit this page History Report an error Markdown