ArticleslgStudy

computer science

Factory method pattern

Factory method pattern is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Factory method pattern rather than just read about it. In short: In object-oriented programming, the factory method pattern is a design pattern that uses factory methods to deal with the problem of creating objects without having to specify their exact classes. Rather than by calling a constructor, this is accomplished by invoking a factory method to create an object.

Factory method pattern — main illustration
Factory method pattern — illustration

Key takeaways

  • Factory method pattern belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Factory method pattern to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Factory method pattern from memory before moving on to harder problems.

Reference excerpt

In object-oriented programming, the factory method pattern is a design pattern that uses factory methods to deal with the problem of creating objects without having to specify their exact classes. Rather than by calling a constructor, this is accomplished by invoking a factory method to create an object. Factory methods can be specified in an interface and implemented by subclasses or implemented in a base class and optionally overridden by subclasses. It is one of the 23 classic design patterns described in the book Design Patterns and is subcategorized as a creational pattern.

Overview The factory method design pattern solves problems such as:

How can an object's subclasses redefine its subsequent and distinct implementation? The pattern involves creation of a factory method within the superclass that defers the object's creation to a subclass's factory method. How can an object's instantiation be deferred to a subclass? Create an object by calling a factory method instead of directly calling a constructor. This enables the creation of subclasses that can change the way in which an object is created (for example, by redefining which class to instantiate).

Definition According to Design Patterns: Elements of Reusable Object-Oriented Software: "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." Creating an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information inaccessible to the composing object, may not provide a sufficient level of abstraction or may otherwise not be included in the composing object's concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created. The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects. The pattern can also rely on the implementation of an interface.

Structure

UML class diagram

In the above UML class diagram, the Creator class that requires a Product object does not instantiate the Product1 class directly. Instead, the Creator refers to a separate factoryMethod() to create a product object, which makes the Creator independent of the exact concrete class that is instantiated. Subclasses of Creator can redefine which class to instantiate. In this example, the Creator1 subclass implements the abstract factoryMethod() by instantiating the Product1 class.

Examples

Structure A maze game may be played in two modes, one with regular rooms that are only connected with adjacent rooms, and one with magic rooms that allow players to be transported at random.

Room is the base class for a final product (MagicRoom or OrdinaryRoom). MazeGame declares the abstract factory method to produce such a base product. MagicRoom and OrdinaryRoom are subclasses of the base product implementing the final product. MagicMazeGame and OrdinaryMazeGame are subclasses of MazeGame implementing the factory method producing the final products. Factory methods thus decouple callers (MazeGame) from the implementation of the concrete classes. This makes the new operator redundant, allows adherence to the open–closed principle and makes the final product more flexible in the event of change.

Example implementations

C++ This C++23 implementation is based on the pre C++98 implementation in the Design Patterns book.

The program output is like

C#

The above code depicts the creation of an interface called IPerson and two implementations called Villager and CityPerson. Based on the type passed to the PersonFactory object, the original concrete object is returned as the interface IPerson. A factory method is just an addition to the PersonFactory class. It creates the object of the class through interfaces but also allows the subclass to decide which class is instantiated.

In this example, MakeProduct is used in concreteFactory. As a result, MakeProduct() may be invoked in order to retrieve it from the IProduct. Custom logic could run after the object is obtained in the concrete factory method. GetObject is made abstract in the factory interface.

Java This Java example is similar to one in the book Design Patterns.

The MazeGame uses Room but delegates the responsibility of creating Room objects to its subclasses that create the concrete classes. The regular game mode could use this template method:

The MazeGame constructor is a template method that adds some common logic. It refers to the makeRoom() factory method that encapsulates the creation of rooms such that other rooms can be used in a subclass. To implement the other game mode that has magic rooms, the makeRoom method may be overridden:

PHP This PHP example shows interface implementations instead of subclassing (however, the same can be achieved through subclassing). The factory method can also be defined as publicand called directly by the client code (in contrast to the previous Java example).

Python This Python example employs the same as did the previous Java example.

Uses In ADO.NET, IDbCommand.CreateParameter is an example of the use of factory method to connect parallel class hierarchies. In Qt, QMainWindow::createPopupMenu Archived 2015-07-19 at the Wayback Machine is a factory method declared in a framework that can be overridden in application code. In Java, several factories are used in the javax.xml.parsers package, such as javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory. In the HTML5 DOM API, the Document interface contains a createElement() factory method for creating specific elements of the HTMLElement interface.

See also Design Patterns, the highly influential book Design pattern, overview of design patterns in general Abstract factory pattern, a pattern often implemented using factory methods Builder pattern, another creational pattern Template method pattern, which may call factory methods Joshua Bloch's idea of a static factory method for which Bloch claims there is no direct equivalent in Design Patterns.

Notes

… excerpt ends here. Continue reading the full article.

Illustrations

Factory method pattern illustration
Factory method pattern illustration

Worked examples

Example 1 — a first encounter with Factory method pattern

Start with the simplest possible case. Write down what Factory method pattern claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Factory method pattern before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Factory method pattern ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Factory method pattern

In research
Factory method pattern appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Factory method pattern in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Factory method pattern is common in secondary-school and first-year university syllabi. It links to neighbouring topics Method (computer programming), Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Factory method pattern outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Factory method pattern” →

How to study Factory method pattern in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Factory method pattern means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Factory method pattern out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Factory method pattern in simple terms?

In object-oriented programming, the factory method pattern is a design pattern that uses factory methods to deal with the problem of creating objects without having to specify their exact classes. Rather than by calling a constructor, this is accomplished by invoking a factory method to create an o…

Why does Factory method pattern matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Factory method pattern?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Factory method pattern.

Tags

  • Method (computer programming)
  • Software design patterns

Keep exploring