Skip to content

2. Creational design patterns

Creational patterns provide object creation mechanisms that increase flexibility and reuse of existing code.

Singleton

Definition

Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

uml diagram

Implementation Details

  1. The Singleton class declares the static method getInstance that returns the same instance of its own class.
  2. The Singleton’s constructor should be hidden from the client code. Calling the getInstance method should be the only way of getting the Singleton object.

Pros and Cons

Pros

  • You can be sure that a class has only a single instance.
  • You gain a global access point to that instance.
  • The singleton object is initialized only when it’s requested for the first time.

Cons

  • Violates the Single Responsibility Principle. The pattern solves two problems at the time.
  • The Singleton pattern can mask bad design, for instance, when the components of the program know too much about each other.
  • The pattern requires special treatment in a multithreaded environment so that multiple threads won’t create a singleton object several times.
  • It may be difficult to unit test the client code of the Singleton because many test frameworks rely on inheritance when producing mock objects.

Usage

  • Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program.
  • Use the Singleton pattern when you need stricter control over global variables.

Factory

Definition

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.

uml diagram

Implementation Details

  1. The Product declares the interface, which is common to all objects that can be produced by the creator and its subclasses.
  2. Concrete Products are different implementations of the product interface.
  3. The Creator class declares the factory method that returns new product objects. It’s important that the return type of this method matches the product interface. You can declare the factory method as abstract to force all subclasses to implement their own versions of the method. As an alternative, the base factory method can return some default product type.

    Note, despite its name, product creation is not the primary responsibility of the creator. Usually, the creator class already has some core business logic related to products. The factory method helps to decouple this logic from the concrete product classes. Here is an analogy: a large software development company can have a training department for programmers. However, the primary function of the company as a whole is still writing code, not producing programmers.

  4. Concrete Creators override the base factory method so it returns a different type of product.

    Note that the factory method doesn’t have to create new instances all the time. It can also return existing objects from a cache, an object pool, or another source.

    Pros and Cons

    Pros

    • You avoid tight coupling between the creator and the concrete products.
    • Single Responsibility Principle. You can move the product creation code into one place in the program, making the code easier to support.
    • Open/Closed Principle. You can introduce new types of products into the program without breaking existing client code.

    Cons

    • The code may become more complicated since you need to introduce a lot of new subclasses to implement the pattern. The best case scenario is when you’re introducing the pattern into an existing hierarchy of creator classes.

    Usage

    • Use the Factory Method when you don’t know beforehand the exact types and dependencies of the objects your code should work with.
    • Use the Factory Method when you want to provide users of your library or framework with a way to extend its internal components.
    • Use the Factory Method when you want to save system resources by reusing existing objects instead of rebuilding them each time.

    Abstract Factory

    Definition

    Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.

uml diagram

Implementation Details

  1. Abstract Products declare interfaces for a set of distinct but related products which make up a product family.
  2. Concrete Products are various implementations of abstract products, grouped by variants. Each abstract product (chair/sofa) must be implemented in all given variants (Victorian/Modern).
  3. The Abstract Factory interface declares a set of methods for creating each of the abstract products.
  4. Concrete Factories implement creation methods of the abstract factory. Each concrete factory corresponds to a specific variant of products and creates only those product variants.
  5. Although concrete factories instantiate concrete products, signatures of their creation methods must return corresponding abstract products. This way the client code that uses a factory doesn’t get coupled to the specific variant of the product it gets from a factory. The Client can work with any concrete factory/product variant, as long as it communicates with their objects via abstract interfaces.

Pros and Cons

Pros

  • You can be sure that the products you’re getting from a factory are compatible with each other.
  • You avoid tight coupling between concrete products and client code.
  • Single Responsibility Principle. You can extract the product creation code into one place, making the code easier to support.
  • Open/Closed Principle. You can introduce new variants of products without breaking existing client code.

Cons

  • The code may become more complicated than it should be, since a lot of new interfaces and classes are introduced along with the pattern.

Usage

  • Use the Abstract Factory when your code needs to work with various families of related products, but you don’t want it to depend on the concrete classes of those products—they might be unknown beforehand or you simply want to allow for future extensibility.

Builder

Definition

Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.

uml diagram

Implementation Details

  1. The Builder interface declares product construction steps that are common to all types of builders.
  2. Concrete Builders provide different implementations of the construction steps. Concrete builders may produce products that don’t follow the common interface.
  3. Products are resulting objects. Products constructed by different builders don’t have to belong to the same class hierarchy or interface.
  4. The Director class defines the order in which to call construction steps, so you can create and reuse specific configurations of products.
  5. The Client must associate one of the builder objects with the director. Usually, it’s done just once, via parameters of the director’s constructor. Then the director uses that builder object for all further construction. However, there’s an alternative approach for when the client passes the builder object to the production method of the director. In this case, you can use a different builder each time you produce something with the director.

Pros and Cons

Pros

  • You can construct objects step-by-step, defer construction steps or run steps recursively.
  • You can reuse the same construction code when building various representations of products.
  • Single Responsibility Principle. You can isolate complex construction code from the business logic of the product.

Cons

  • The overall complexity of the code increases since the pattern requires creating multiple new classes.

Usage

  • Use the Builder pattern to get rid of a telescoping constructor.
  • Use the Builder pattern when you want your code to be able to create different representations of some product (for example, stone and wooden houses).
  • Use the Builder to construct Composite trees or other complex objects.

Prototype

Definition

Prototype is a creational design pattern that lets you copy existing objects without making your code dependent on their classes.

uml diagram

Implementation Details

  1. The Prototype interface declares the cloning methods. In most cases, it’s a single clone method.
  2. The Concrete Prototype class implements the cloning method. In addition to copying the original object’s data to the clone, this method may also handle some edge cases of the cloning process related to cloning linked objects, untangling recursive dependencies, etc.
  3. The Client can produce a copy of any object that follows the prototype interface.

Pros and Cons

Pros

  • You can clone objects without coupling to their concrete classes.
  • You can get rid of repeated initialization code in favor of cloning pre-built prototypes.
  • You can produce complex objects more conveniently.
  • You get an alternative to inheritance when dealing with configuration presets for complex objects.

Cons

  • Cloning complex objects that have circular references might be very tricky.

Usage

  • Use the Prototype pattern when your code shouldn’t depend on the concrete classes of objects that you need to copy.
  • Use the pattern when you want to reduce the number of subclasses that only differ in the way they initialize their respective objects.