SWE : Creational Design Pattern

Part 2 of Design Pattern series

Pisit J.
Pisit J.
Mar 4 · 4 min read
image

1. Abstract Factory

  • Client works with factories and products using abstract interfaces. It makes the same client code working with many product variants, depending on the type of factory object.

Pros

  • You can introduce new variants of products without breaking existing client code.

Cons

Example

  • In this example, buttons and checkboxes will act as products. They have two variants: macOS and Windows.
Factory
GUI Application (Client Code)
Main
Output

Reference

2. Builder

  • The base Builder interface defines all possible construction steps, and concrete builders implement these steps to construct particular representations of the product.
  • Meanwhile, the Director class defines the order of construction.
  • You can swap or defer execution of some steps without breaking the final product.
  • Builder doesn’t expose the final product until construction is complete.

Pros

Cons

Example

Builder — defines all possible construction steps
Director — defines the order of construction
Main

Reference

3. Prototype

  • Delegates the cloning process to the actual objects that are being cloned. The pattern declares a common interface for all objects that support cloning.

Pros

Cons

Example

Prototype
Class extends Prototype
Main
Output

Reference

4. Singleton

  • Ensure a class has only one instance, and provide a global point of access.
  • Unlike global variables, Singleton make sure that there’s just one instance of a class. Only the Singleton itself can replace the cached instance.

Pros

Cons

Example

  1. Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
  2. Create a static creation method that acts as a constructor. This method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.
Singleton
Main
Output

Reference