Factory Pattern

Factories

  • A Very Simple Factory
  • Factory Method
  • Abstract Factory

When to use factories?

  • Unsure which concrete implementation of an interface I want to return
  • Creation should be seperated from representation of an object
  • Lots of if/else blocks when deciding which concrete class to create
  • Switch statements when deciding which concrete class to create

Simple Factory

Intent

  • Creates objects without exposing the instantiation logic to the client
  • Refers to the newly created object through a common interface

Implementation

Example Model

Factory Method

Intent

  • Defines an interface for creating objects, but let subclasses to decide which class to instantiate
  • Refers to the newly created object through a common interface

Implementation

Example Model

Advantage

  • Eliminate references to concrete classes
    • Factories
    • Objects created by factories
  • Factories can be inherited to provide even more specialized object creation
  • Rules for object initialization is centralized

Disadvantage

  • May ned to create a factory just to get a concrete class delivered
  • The inheritance hierarchy gets deeper with coupling between concrete factories and created classes

Abstract Factory

Intent

  • Offers the interface for creating a family of related objects, without explicitly specifying their classes
  • Factories create different types of concrete objects(Products)
  • A Factory now represents a "family" of objects that it can create
  • Factories may have more than one factory method

Implementation

  • AbstractFactory - declares a interface for operations that create abstract products
  • ConcreteFactory - implements operations to create concrete products
  • AbstractProduct - declares an interface for a type of product objects
  • Product - defines a product to be created by the corresponding ConcreteFactory; it implements the AbstractProduct interface
  • Client - uses the interfaces declared by the AbstractFactory and AbstractProduct classes

Example Model

Consequences

  • Add new factories and classes without breaking OCP
  • Defer choosing classes to classes that specialized in making that decision
  • Using private or internal constructors hides direct construction with the "new" keyword

Resources

thanks....

@brs_snmz

Design Patterns: Factory Pattern

By Barış SÖNMEZ

Design Patterns: Factory Pattern

  • 341