Creational Software Design Patterns

Image Source

This article will explore what creational design patterns are, why we need them and what different variations exist.

Creational design patterns are the mechanisms for object creation in software engineering. They control the way objects are created and hence, increase the flexibility of the system.

The main aim of these patterns is to separate the creation of objects from their usage, thereby improving the quality and re-usability of your code.

To understand this better, consider the following code that does not follow the basic creational design patterns:

public class Bird {
Beak beak;

public void eat() {
beak.eat();
}
public Bird() {
beak = new Beak();
}
}
public class Beak {
public void eat() {

}
}

Bird instantiates its Beak, and only via the interface of Bird will you be able to make the beak eat. This design is bad because you cannot change the Beak a bird has, which might become a problem in case you’re testing this code and want to swap things. Therefore, this design needs a slight improvement in line with the patterns described below.

An interface or abstract class is defined but the subclasses decide which class to instantiate.

When to Use:

  1. You don’t know exactly the types of objects your code will be working with in advance.
  2. You want to provide a way for users to easily extend and/or override the class methods.
  3. You want to provide a way to easily re-use the existing code.
Image Source

An interface or abstract class to create families of related objects. You can think of it as the abstract class of the abstract classes for factory method patterns.

When to Use:

  1. You want to separate the system entirely from how its objects are created.
  2. You want to use the family of related objects together.
  3. You want to only show the interfaces of objects without actual implementation.
Image Source

Constructing an object step-by-step, out of simpler objects.

When to Use:

  1. You want a clear separation of object representation from its construction.
  2. You want to have control over constructing the object and be able to change things at different levels.
Image Source

Clone an existing object for new usage instead of creating a new object.

When to Use:

  1. You want to keep the number of objects at a minimum.
  2. You want to keep the cost of creating new objects at a minimum, if the cost is expensive.
  3. You want to add or remove objects at runtime.
Image Source

A class with just one instance and there’s one global access to it.

When to Use:

  1. You want to use objects in multi-threaded and database applications: for example, a single database object shared by different parts of the program. (Source)
  2. You want to have strict control over global variables.
Image Source

Computer Science & Data Analytics Master Student @ADA & @GWU