Patterncore
Factory Method pattern
Also called Factory Method, virtual constructor.
A base class does its work through an abstract product and gets the product from a method that subclasses override. Each subclass decides which concrete class to create.
- Family
- creational-design
- Intent
- Define an operation that creates an object, and let subclasses decide which class to create, so that the code that uses the object does not name a concrete class.
- Also called
- Virtual Constructor
- Refactorings
- Introduce polymorphic creation with factory method
Intent
Define an operation that creates an object, and let subclasses decide which class to create. The code that uses the object works with an interface and does not name a concrete class.1
Problem
An exporter writes a table of rows. It writes a header, then one line for each row. The steps are the same for every format, but the class that formats the lines is different. One class writes CSV, and another writes text for a person to read. A user of a library will want a third format that the authors did not plan.
The direct design creates the writer inside export with a conditional on a format name, or with a call to one concrete constructor. Either way, the exporter names every concrete writer. A third format needs a change to the exporter. The library cannot ship the export loop and let its users supply the format.
The forces are these. The algorithm that uses the object is fixed and belongs in one place. The concrete class of the object is not known when that algorithm is written. The class must be chosen by code that comes later, often by a subclass in another module. Kerievsky describes a related starting point: classes in a hierarchy implement a method in the same way, except for the step that creates an object.3
Solution
Put the creation step in its own method, the factory method, and call it from the algorithm. The base class, the creator, declares the factory method with the type of the abstract product. Each concrete creator overrides the factory method and returns a concrete product.1
Creator (Exporter) Product (Writer)
------------------------------ ----------------
export(rows): header()
w = create_writer() ---creates--> row(name, count)
w.header(); w.row(...) ... ^
create_writer(): Writer (abstract) |
^ +-------+-------+
| | |
+-----+--------+ CsvWriter TextWriter
| | ^ ^
CsvExporter TextExporter | |
create_writer() --------------------->+ |
create_writer() ---------------------->+
The participants in Design Patterns are Product, ConcreteProduct, Creator and ConcreteCreator.1 The creator depends only on the product interface. Only the concrete creator names the concrete product.
The method that calls the factory method is often a template method. It fixes the order of the steps and leaves one step, the creation, to subclasses. Design Patterns notes this link in its Related Patterns section for Factory Method.1
Design Patterns describes two main forms. In the first, the creator is abstract and has no default product. In the second, the creator is concrete and returns a default product, and subclasses override it only to change it. A parameterized factory method takes an argument, such as a format name, and returns one of several products. Subclasses can then extend or override the choice for some values of the argument.1
In languages where classes and functions are values, the subclass is often not needed. If a class is a value, the creator can store the class and call it. If a function is a value, the creator can store a function that returns a product. Norvig counts Factory Method among the six patterns that first-class types make simpler.2 The standard libraries use this form:
| Language | Factory as a value |
|---|---|
| Python | a class is callable, and collections.defaultdict takes a default_factory such as list11 |
| Java | java.util.function.Supplier<T>, with a constructor reference such as CsvWriter::new910 |
| Go | a constructor function that returns an interface, such as crc32.NewIEEE returning hash.Hash3212 |
| Rust | a trait with a default method that calls a required factory method14 |
| Kotlin | a top-level factory function, which the coding conventions describe15 |
The factory-as-a-value form is the Strategy pattern applied to creation. The subclass form fixes the choice when the subclass is written. The value form lets the choice change when the creator is built.
Example
The example files show one program in each language. An exporter writes the rows ("pen", 3) and ("book", 1). The CSV exporter makes a CSV writer, and the text exporter makes a text writer. The method export is the same for both and calls the factory method once:
| Language | Form |
|---|---|
| Python | an abstract base class with abc.abstractmethod16 |
| JavaScript | a base class whose createWriter throws until a subclass overrides it |
| TypeScript | an abstract class and an abstract method |
| Java | an abstract class, and concrete products as records |
| Kotlin | an abstract class with an abstract fun |
| C# | an abstract class with an abstract method |
| C++ | a pure virtual function that returns std::unique_ptr<Writer> |
| Go | an interface with a NewWriter method, and Export as a function that takes it |
| Rust | a trait with an associated type, a required create_writer and a default export |
from abc import ABC, abstractmethod
class Writer(ABC):
@abstractmethod
def header(self) -> str: ...
@abstractmethod
def row(self, name: str, count: int) -> str: ...
class CsvWriter(Writer):
def header(self) -> str:
return "name,count"
def row(self, name: str, count: int) -> str:
return f"{name},{count}"
class TextWriter(Writer):
def header(self) -> str:
return "Inventory"
def row(self, name: str, count: int) -> str:
return f"{name}: {count}"
class Exporter(ABC):
def export(self, rows: list[tuple[str, int]]) -> str:
writer = self.create_writer() # the factory method
lines = [writer.header()]
lines += [writer.row(name, count) for name, count in rows]
return "\n".join(lines)
@abstractmethod
def create_writer(self) -> Writer: ...
class CsvExporter(Exporter):
def create_writer(self) -> Writer:
return CsvWriter()
class TextExporter(Exporter):
def create_writer(self) -> Writer:
return TextWriter()
rows = [("pen", 3), ("book", 1)]
for exporter in [CsvExporter(), TextExporter()]:
print(exporter.export(rows))
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom. Python has no construct for the pattern. A method that subclasses override is the classic form, and
abc.abstractmethodstops code from creating anExporterthat has no factory method. - A class is a callable that returns an instance, so the usual Python form passes the class itself:
Exporter(make_writer=CsvWriter). The node page shows this variant. collections.defaultdict(list)uses the same idea in the standard library:listis the factory that makes each missing value.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
struct Writer {
virtual ~Writer() = default;
virtual std::string header() const = 0;
virtual std::string row(const std::string& name, int count) const = 0;
};
struct CsvWriter : Writer {
std::string header() const override { return "name,count"; }
std::string row(const std::string& name, int count) const override {
return name + "," + std::to_string(count);
}
};
struct TextWriter : Writer {
std::string header() const override { return "Inventory"; }
std::string row(const std::string& name, int count) const override {
return name + ": " + std::to_string(count);
}
};
using Rows = std::vector<std::pair<std::string, int>>;
class Exporter {
public:
virtual ~Exporter() = default;
std::string export_rows(const Rows& rows) const {
const std::unique_ptr<Writer> writer = create_writer(); // the factory method
std::string out = writer->header();
for (const auto& [name, count] : rows) {
out += "\n" + writer->row(name, count);
}
return out;
}
protected:
virtual std::unique_ptr<Writer> create_writer() const = 0;
};
class CsvExporter : public Exporter {
protected:
std::unique_ptr<Writer> create_writer() const override {
return std::make_unique<CsvWriter>();
}
};
class TextExporter : public Exporter {
protected:
std::unique_ptr<Writer> create_writer() const override {
return std::make_unique<TextWriter>();
}
};
int main() {
const Rows rows{{"pen", 3}, {"book", 1}};
const CsvExporter csv;
const TextExporter text;
for (const Exporter* exporter : {static_cast<const Exporter*>(&csv), static_cast<const Exporter*>(&text)}) {
std::cout << exporter->export_rows(rows) << "\n";
}
}
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom. A pure virtual function is the factory method. It returns
std::unique_ptr<Writer>, so the caller owns the product and the type says so. - The method is named
export_rowsbecauseexportis a keyword in C++. export_rowsis not virtual, so it is a template method with one hook. The factory method is called there, not in the constructor ofExporter(see the node page).- A template parameter,
Exporter<CsvWriter>, is the compile-time form with no creator subclass, as Design Patterns describes for C++.
import java.util.ArrayList;
import java.util.List;
public class Main {
interface Writer {
String header();
String row(String name, int count);
}
record CsvWriter() implements Writer {
public String header() {
return "name,count";
}
public String row(String name, int count) {
return name + "," + count;
}
}
record TextWriter() implements Writer {
public String header() {
return "Inventory";
}
public String row(String name, int count) {
return name + ": " + count;
}
}
record Row(String name, int count) {}
abstract static class Exporter {
final String export(List<Row> rows) {
Writer writer = createWriter(); // the factory method
List<String> lines = new ArrayList<>();
lines.add(writer.header());
for (Row r : rows) {
lines.add(writer.row(r.name(), r.count()));
}
return String.join("\n", lines);
}
protected abstract Writer createWriter();
}
static final class CsvExporter extends Exporter {
@Override
protected Writer createWriter() {
return new CsvWriter();
}
}
static final class TextExporter extends Exporter {
@Override
protected Writer createWriter() {
return new TextWriter();
}
}
public static void main(String[] args) {
List<Row> rows = List.of(new Row("pen", 3), new Row("book", 1));
for (Exporter exporter : List.of(new CsvExporter(), new TextExporter())) {
System.out.println(exporter.export(rows));
}
}
}
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom. The classic form: an abstract creator with a
protected abstractfactory method.exportisfinal, so subclasses can change only the creation step. - A
Supplier<Writer>field with a constructor reference such asCsvWriter::newis the form with no creator subclass. - A static factory method such as
List.ofis a different technique. It cannot be overridden, so it is not this pattern.
var rows = new (string Name, int Count)[] { ("pen", 3), ("book", 1) };
foreach (Exporter exporter in new Exporter[] { new CsvExporter(), new TextExporter() })
{
Console.WriteLine(exporter.Export(rows));
}
interface IWriter
{
string Header();
string Row(string name, int count);
}
sealed class CsvWriter : IWriter
{
public string Header() => "name,count";
public string Row(string name, int count) => $"{name},{count}";
}
sealed class PlainTextWriter : IWriter
{
public string Header() => "Inventory";
public string Row(string name, int count) => $"{name}: {count}";
}
abstract class Exporter
{
public string Export(IEnumerable<(string Name, int Count)> rows)
{
IWriter writer = CreateWriter(); // the factory method
var lines = new List<string> { writer.Header() };
lines.AddRange(rows.Select(r => writer.Row(r.Name, r.Count)));
return string.Join("\n", lines);
}
protected abstract IWriter CreateWriter();
}
sealed class CsvExporter : Exporter
{
protected override IWriter CreateWriter() => new CsvWriter();
}
sealed class TextExporter : Exporter
{
protected override IWriter CreateWriter() => new PlainTextWriter();
}
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom. The classic form: an
abstractclass with aprotected abstractfactory method. Methods in C# are not virtual unless declared so, soExportcannot be overridden. - The product is named
PlainTextWriter, because the implicit usings of a .NET project importSystem.IO, which has aTextWriterclass of its own. - A
Func<IWriter>parameter is the form with no creator subclass. TheMicrosoft.Extensions.DependencyInjectioncontainer can also build a writer by type.
class CsvWriter {
header() {
return "name,count";
}
row(name, count) {
return `${name},${count}`;
}
}
class TextWriter {
header() {
return "Inventory";
}
row(name, count) {
return `${name}: ${count}`;
}
}
class Exporter {
export(rows) {
const writer = this.createWriter(); // the factory method
return [writer.header(), ...rows.map(([name, count]) => writer.row(name, count))].join("\n");
}
createWriter() {
throw new Error(`${this.constructor.name} must override createWriter`);
}
}
class CsvExporter extends Exporter {
createWriter() {
return new CsvWriter();
}
}
class TextExporter extends Exporter {
createWriter() {
return new TextWriter();
}
}
const rows = [
["pen", 3],
["book", 1],
];
for (const exporter of [new CsvExporter(), new TextExporter()]) {
console.log(exporter.export(rows));
}
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom. JavaScript has no abstract methods, so the base
createWriterthrows until a subclass overrides it. The product interface is by convention: any object withheaderandrowworks. - A class is a value, so a creator can also take the class and call
new this.Writer(), or take a function that returns a writer. This removes the creator subclasses.
interface Writer {
header(): string;
row(name: string, count: number): string;
}
class CsvWriter implements Writer {
header(): string {
return "name,count";
}
row(name: string, count: number): string {
return `${name},${count}`;
}
}
class TextWriter implements Writer {
header(): string {
return "Inventory";
}
row(name: string, count: number): string {
return `${name}: ${count}`;
}
}
abstract class Exporter {
export(rows: ReadonlyArray<readonly [string, number]>): string {
const writer = this.createWriter(); // the factory method
return [writer.header(), ...rows.map(([name, count]) => writer.row(name, count))].join("\n");
}
protected abstract createWriter(): Writer;
}
class CsvExporter extends Exporter {
protected createWriter(): Writer {
return new CsvWriter();
}
}
class TextExporter extends Exporter {
protected createWriter(): Writer {
return new TextWriter();
}
}
const rows = [
["pen", 3],
["book", 1],
] as const;
const exporters: Exporter[] = [new CsvExporter(), new TextExporter()];
for (const exporter of exporters) {
console.log(exporter.export(rows));
}
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom.
abstractclasses and methods are part of TypeScript's type system. The compiler rejectsnew Exporter()and a subclass that does not implementcreateWriter. abstractandprotecteddisappear when the types are stripped, so they are compile-time checks only.- A constructor type such as
new () => Writerlets a creator take the class of the product as a value, with no creator subclass.
package main
import (
"fmt"
"strings"
)
type Writer interface {
Header() string
Row(name string, count int) string
}
type csvWriter struct{}
func (csvWriter) Header() string { return "name,count" }
func (csvWriter) Row(name string, count int) string { return fmt.Sprintf("%s,%d", name, count) }
type textWriter struct{}
func (textWriter) Header() string { return "Inventory" }
func (textWriter) Row(name string, count int) string { return fmt.Sprintf("%s: %d", name, count) }
// Exporter is the creator. Go has no inheritance, so the factory method is
// an interface method, and the template method is a function that takes it.
type Exporter interface {
NewWriter() Writer
}
type Row struct {
Name string
Count int
}
func Export(e Exporter, rows []Row) string {
w := e.NewWriter() // the factory method
lines := []string{w.Header()}
for _, r := range rows {
lines = append(lines, w.Row(r.Name, r.Count))
}
return strings.Join(lines, "\n")
}
type CSVExporter struct{}
func (CSVExporter) NewWriter() Writer { return csvWriter{} }
type TextExporter struct{}
func (TextExporter) NewWriter() Writer { return textWriter{} }
func main() {
rows := []Row{{"pen", 3}, {"book", 1}}
for _, e := range []Exporter{CSVExporter{}, TextExporter{}} {
fmt.Println(Export(e, rows))
}
}
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom. Go has no inheritance, so a base type cannot call a method that a "subclass" overrides. The factory method becomes a method of an interface, and the shared algorithm is a function over that interface.
- Embedding a struct does not help. A method of the embedded struct calls its own methods, not the methods of the outer type.
- The usual Go form is simpler: pass a
func() Writer, or call a constructor function that returns the interface, ascrc32.NewIEEEreturns ahash.Hash32.
trait Writer {
fn header(&self) -> String;
fn row(&self, name: &str, count: u32) -> String;
}
struct CsvWriter;
impl Writer for CsvWriter {
fn header(&self) -> String {
"name,count".to_string()
}
fn row(&self, name: &str, count: u32) -> String {
format!("{name},{count}")
}
}
struct TextWriter;
impl Writer for TextWriter {
fn header(&self) -> String {
"Inventory".to_string()
}
fn row(&self, name: &str, count: u32) -> String {
format!("{name}: {count}")
}
}
trait Exporter {
type Product: Writer;
// The factory method: each implementation must supply it.
fn create_writer(&self) -> Self::Product;
// A default method that calls the factory method.
fn export(&self, rows: &[(&str, u32)]) -> String {
let writer = self.create_writer();
let mut lines = vec![writer.header()];
lines.extend(rows.iter().map(|(name, count)| writer.row(name, *count)));
lines.join("\n")
}
}
struct CsvExporter;
impl Exporter for CsvExporter {
type Product = CsvWriter;
fn create_writer(&self) -> CsvWriter {
CsvWriter
}
}
struct TextExporter;
impl Exporter for TextExporter {
type Product = TextWriter;
fn create_writer(&self) -> TextWriter {
TextWriter
}
}
fn main() {
let rows = [("pen", 3), ("book", 1)];
println!("{}", CsvExporter.export(&rows));
println!("{}", TextExporter.export(&rows));
}
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom. Rust has no inheritance, but a trait with a default method gives the same shape. The default
exportcalls the requiredcreate_writer, and each type supplies it. - The associated type
Productfixes the product type for each exporter at compile time, so the call needs no allocation and no vtable. - An associated type makes
Exporterunusable asdyn Exporterwithout namingProduct. A list of mixed exporters needsfn create_writer(&self) -> Box<dyn Writer>instead. CsvWriter::new()style functions are not the pattern. They are static, inherent methods, the Rust convention for constructors.
interface Writer {
fun header(): String
fun row(name: String, count: Int): String
}
class CsvWriter : Writer {
override fun header() = "name,count"
override fun row(name: String, count: Int) = "$name,$count"
}
class TextWriter : Writer {
override fun header() = "Inventory"
override fun row(name: String, count: Int) = "$name: $count"
}
abstract class Exporter {
fun export(rows: List<Pair<String, Int>>): String {
val writer = createWriter() // the factory method
return (listOf(writer.header()) + rows.map { (name, count) -> writer.row(name, count) })
.joinToString("\n")
}
protected abstract fun createWriter(): Writer
}
class CsvExporter : Exporter() {
override fun createWriter(): Writer = CsvWriter()
}
class TextExporter : Exporter() {
override fun createWriter(): Writer = TextWriter()
}
fun main() {
val rows = listOf("pen" to 3, "book" to 1)
for (exporter in listOf(CsvExporter(), TextExporter())) {
println(exporter.export(rows))
}
}
name,count
pen,3
book,1
Inventory
pen: 3
book: 1
- Verdict: idiom. Kotlin classes and methods are final unless they are
openorabstract, soexportcannot be overridden and onlycreateWritervaries. - A constructor parameter of type
() -> Writer, given::CsvWriter, is the form with no creator subclass. - A factory function at the top level, or in a
companion object, is the Kotlin form of a static factory. It is not the pattern, because it cannot be overridden.
Consequences
Design Patterns lists these benefits.1 The code that uses the product does not name a concrete class, so it works with any class that implements the product interface. The factory method is a hook: a subclass can give an extended version of an object with no change to the creator. A factory method can connect parallel class hierarchies. In the example, each exporter knows which writer goes with it, and nothing else in the program needs that knowledge.
The main cost is the subclass. A client may have to subclass the creator only to create one particular product.1 Each format in the example needs two classes: a writer and an exporter. When the exporter adds nothing but the choice of the writer, the second class is noise. Pass the writer's class or a factory function to the exporter instead, as in the variant below.
Do not call the factory method from the constructor of the creator. The creator is not fully built when its constructor runs, and languages handle a virtual call at that time in two different ways. In C++, a virtual call from a constructor calls the version of the class whose constructor runs, not the override of the more derived class.5 The text exporter below gets a CSV writer:
This code runs but gives a wrong answer on purpose.
#include <iostream>
#include <memory>
#include <string>
struct Writer {
virtual ~Writer() = default;
virtual std::string row(const std::string& name, int count) const = 0;
};
struct CsvWriter : Writer {
std::string row(const std::string& name, int count) const override {
return name + "," + std::to_string(count);
}
};
struct TextWriter : Writer {
std::string row(const std::string& name, int count) const override {
return name + ": " + std::to_string(count);
}
};
class Exporter {
public:
Exporter() : writer_(create_writer()) {} // a virtual call in the constructor
virtual ~Exporter() = default;
std::string export_row(const std::string& name, int count) const {
return writer_->row(name, count);
}
protected:
virtual std::unique_ptr<Writer> create_writer() const {
return std::make_unique<CsvWriter>();
}
private:
std::unique_ptr<Writer> writer_;
};
class TextExporter : public Exporter {
protected:
std::unique_ptr<Writer> create_writer() const override {
return std::make_unique<TextWriter>();
}
};
int main() {
TextExporter exporter;
std::cout << exporter.export_row("pen", 3) << "\n";
}
pen,3
In Java, the call goes to the override, but the override runs before the fields of the subclass have their values. The Java Language Specification states this: overriding methods are used even before the object is completely initialized.6 Here the separator is still null:
This code runs but gives a wrong answer on purpose.
public class Main {
interface Writer {
String row(String name, int count);
}
abstract static class Exporter {
private final Writer writer;
Exporter() {
writer = createWriter(); // an overridable call in the constructor
}
abstract Writer createWriter();
String exportRow(String name, int count) {
return writer.row(name, count);
}
}
static final class TextExporter extends Exporter {
private final String separator;
TextExporter(String separator) {
this.separator = separator;
}
@Override
Writer createWriter() {
String sep = separator;
return (name, count) -> name + sep + count;
}
}
public static void main(String[] args) {
System.out.println(new TextExporter(": ").exportRow("pen", 3));
}
}
pennull3
Bloch gives the general rule for classes designed for inheritance: constructors must not invoke overridable methods.8 The usual fix is to call the factory method later, in the operation that needs the product, as the example files do in export. Design Patterns describes a lazy accessor in C++ for the same reason: it creates the product on first use.1 Java has one more fix for this case. A constructor can assign its fields in the prologue, which is the statements before the super() call. Then the fields have their values when the superclass constructor runs.67
public class Main {
interface Writer {
String row(String name, int count);
}
abstract static class Exporter {
private final Writer writer;
Exporter() {
writer = createWriter();
}
abstract Writer createWriter();
String exportRow(String name, int count) {
return writer.row(name, count);
}
}
static final class TextExporter extends Exporter {
private final String separator;
TextExporter(String separator) {
this.separator = separator; // the prologue runs before super()
super();
}
@Override
Writer createWriter() {
String sep = separator;
return (name, count) -> name + sep + count;
}
}
public static void main(String[] args) {
System.out.println(new TextExporter(": ").exportRow("pen", 3));
}
}
pen: 3
A static factory method is a different thing. Bloch's Item 1 recommends static methods such as valueOf or of in place of public constructors. He notes that a static factory method is not the Factory Method pattern of Design Patterns.8 A static method cannot be overridden, so it gives a named constructor and a choice of the returned class, but not the subclass hook. In Rust, the convention is that a constructor is a static, inherent method, often named new, so the same distinction applies.13
When not to use it
Do not use the pattern when there is one product class and no plan for another. A direct constructor call is clearer, and the reader sees which class runs.
Do not add a creator subclass whose only job is to choose a product. Pass the product's class, a constructor reference, or a factory function to the creator. This keeps one class for each format instead of two.
Do not use a factory method to hide a choice that the caller should make. When the caller knows the concrete class and needs its specific methods, the abstract return type only forces a cast later.
A program where every new goes through a factory method has many classes and little behaviour. Kerievsky's catalog starts from duplicated creation code, and the refactoring is worth its cost when that duplication is real.3
Variants and related patterns
Factory as a parameter. The creator takes a callable that makes the product. In Python a class is such a callable, so the exporter needs no subclasses:
class CsvWriter:
def row(self, name, count):
return f"{name},{count}"
class TextWriter:
def __init__(self, separator=": "):
self.separator = separator
def row(self, name, count):
return f"{name}{self.separator}{count}"
class Exporter:
def __init__(self, make_writer):
self.make_writer = make_writer
def export(self, rows):
writer = self.make_writer()
return "\n".join(writer.row(name, count) for name, count in rows)
rows = [("pen", 3), ("book", 1)]
print(Exporter(CsvWriter).export(rows))
print(Exporter(lambda: TextWriter(" = ")).export(rows))
pen,3
book,1
pen = 3
book = 1
Abstract Factory. An abstract factory is an object with several factory methods, one for each product of a family. Design Patterns notes that abstract factories are often implemented with factory methods.1
Template Method. The operation that calls the factory method is usually a template method, and the factory method is one of its hook steps.1
Prototype. Design Patterns contrasts the two. Prototype does not need a subclass of the creator, because it copies an instance that the client gives. But it often needs an initialize operation on the product.1
Dependency injection. A container that builds the objects of a program and passes them in is a general factory, configured in one place. In his 2009 draft of a revised catalog, Gamma proposed to generalize Factory Method to Factory and to add Dependency Injection as a pattern.4
Singleton. A concrete factory often has one instance in a program. Design Patterns makes this point in its section on Abstract Factory.19 The Singleton pattern page explains why passing the factory in is often better than a global instance.
Known uses
- OpenJDK:
java.util.AbstractCollectiondeclaresiterator()as abstract. contains in AbstractCollection.java at jdk-25+36 callsiterator()and walks the result, socontains,toStringand other methods work for every collection. ArrayList.iterator at jdk-25+36 overrides it and returns its own iterator class. The collections and their iterators are parallel hierarchies.1718
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 3, Factory Method (Intent, Also Known As, Motivation, Participants, Consequences, Implementation, Related Patterns)
- Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 10 (first-class types make Abstract-Factory, Flyweight, Factory-Method, State, Proxy and Chain-Of-Responsibility simpler)
- Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 6, Creation, Introduce Polymorphic Creation with Factory Method (problem and solution)
- Larry O'Brien, Design Patterns 15 Years Later, An Interview with Erich Gamma, Richard Helm, and Ralph Johnson, InformIT, October 22, 2009, Gamma's draft of a revised catalog (generalize Factory Method to Factory; add Dependency Injection)
- Working Draft, Programming Languages, C++ (N4950), [class.cdtor] paragraph 4 (virtual calls during construction)
- The Java Language Specification, Java SE 25 Edition, 12.5 Creation of New Class Instances (the note after the procedure, on overriding methods during creation)
- The Java Language Specification, Java SE 25 Edition, 8.8.7 Constructor Body (prologue and epilogue)
- Joshua Bloch, Effective Java, third edition, Addison-Wesley, 2018, Item 1, Consider static factory methods instead of constructors; Item 19, Design and document for inheritance or else prohibit it
- Java SE 25 API, java.util.function.Supplier, interface description
- The Java Language Specification, Java SE 25 Edition, 15.13 Method Reference Expressions (ClassType :: new)
- The Python Standard Library, collections, Python 3.14, defaultdict.default_factory
- Effective Go, Interfaces and other types, Generality
- Rust API Guidelines, Predictability, C-CTOR, Constructors are static, inherent methods
- The Rust Programming Language, chapter 10.2, Using Default Implementations
- Kotlin coding conventions, Factory functions
- The Python Standard Library, abc, Python 3.14, abc.abstractmethod
- OpenJDK jdk-25+36 source, java/util/AbstractCollection.java, contains, lines 104 to 116
- OpenJDK jdk-25+36 source, java/util/ArrayList.java, iterator, lines 1029 to 1031
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 3, Abstract Factory (Implementation, factories as singletons)
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 0PK16R Edit this page History Report an error Markdown