The What & The Why
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.
Factory Method Pattern
An interface or abstract class is defined but the subclasses decide which class to instantiate.
When to Use:
- You don’t know exactly the types of objects your code will be working with in advance.
- You want to provide a way for users to easily extend and/or override the class methods.
- You want to provide a way to easily re-use the existing code.
Abstract Factory Pattern
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:
- You want to separate the system entirely from how its objects are created.
- You want to use the family of related objects together.
- You want to only show the interfaces of objects without actual implementation.
Builder Pattern
Constructing an object step-by-step, out of simpler objects.
When to Use:
- You want a clear separation of object representation from its construction.
- You want to have control over constructing the object and be able to change things at different levels.
Prototype Pattern
Clone an existing object for new usage instead of creating a new object.
When to Use:
- You want to keep the number of objects at a minimum.
- You want to keep the cost of creating new objects at a minimum, if the cost is expensive.
- You want to add or remove objects at runtime.
Singleton Pattern
A class with just one instance and there’s one global access to it.
When to Use:
- 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)
- You want to have strict control over global variables.