Design Patterns Explained
  • Getting Started
  • SOLID Principles
    • Single Responsibility Principle
    • Open / Closed Principle
    • Liskov Substitution Principle
    • Interface Segregation Principle
    • Dependency Inversion Principle
  • Design Patterns
    • Creational Patterns
      • Abstract Factory Pattern
      • Builder Pattern
      • Factory Pattern
      • Prototype Pattern
      • Singleton Pattern
    • Behavioral Patterns
      • Chain Of Responsibility Pattern
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
        • Example 1
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
        • Example 1
      • Template Method Pattern
      • Visitor Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Decorator Pattern
      • Facade Pattern
      • Flyweight Pattern
      • Proxy Pattern
  • Roadmap
Powered by GitBook
On this page
  • Intent
  • When to use
  • Structure
  • Implementation
  • Examples

Was this helpful?

  1. Design Patterns
  2. Creational Patterns

Factory Pattern

PreviousBuilder PatternNextPrototype Pattern

Last updated 3 years ago

Was this helpful?

Intent

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.

When to use

  1. You can't know the type of object you want to create until runtime.

  2. You want to encapsulate the object creation logic if some complexity or business logic takes place, or for easier extraction and modification later on.

Structure

  • Product: declares the interface of the object the factory method will create.

  • ConcreteProduct: implements the Product interface.

  • Creator: declares the factory method which returns an object of type Product, it may also implement a basic factory method which can be overriden by subclasses.

  • ConcreteCreator: implements the factory method to return an instance of a ConcreteProduct.

Implementation

Factory method can have 2 types of implementations:

  1. Relying on subclasses for the Factory that returns different kind of ConcreteProducts (doesn't violate the O/C Principle, allows for polymorphism, and Dependency Injection).

  2. Relying on a paramater (Parametrized Factory) to determine the type of the ConcreteProduct needed.

Examples

Source Code
UML

// TODO

// TODO

// TODO

You can find the tests .

here
Example 1
Example 2
Example 3