Skip to main content

Gangs of Four (GoF) Design Patterns

Overview​

Deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. These patterns help in making a system independent of how its objects are created, composed, and represented.

NameVisualizationDefinitionExample
Singleton
  • ensures a class has only one instance and provides a global point of access to it
database connection manager in a web application
Factory
  • interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created
  • implementation via inheritance
  • creates 1 product
different factories produce different types of vehicles (car, truck)
Abstract Factory
  • interface for creating families of related or dependent objects without specifying their concrete classes
  • implementation via composition
  • creates families of the products
GUI toolkit providing different look and feel for different operating systems
Builder
  • separates the construction of a complex object from its representation, allowing the same construction process to create various representations
  • constructs complex objects step by step
construction of complex objects like HTML documents
Prototype
  • specifies the kinds of objects to create using a prototypical instance, and creates new objects by copying this prototype
  • creates a copy (clone) of an object
creating multiple instances of a document (cloning objects) with different content but similar structure

Factory vs Abstract Factory

AspectFactory MethodAbstract Factory
Product Typecreates one product onlycreates families of related or dependent products
Exposureexposes a method to create the objectexposes a family of related objects
Construction Hidinghides the construction of a single objecthides the construction of a family of related objects. Abstract factories are usually implemented using (a set of) factory methods
Creation Responsibilityuses inheritance and relies on a derived class or subclass to create an objectuses composition to delegate the responsibility of creating an object to another class
Ideal Usagebest for cases where the client doesn't know what concrete classes it will be required to create at runtimebest utilized when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details