Design Pattern: Factory Pattern

Summary

Pattern NameFactory Pattern
Pattern TypeCreational Pattern
ScopeClass
Other NamesVirtual Constructor
TaglineGenerate objects based on selected criteria
Use cases1. When we don’t know the type of object to be generated beforehand
2. When we want to generate the object on the fly based on some criteria
Related PatternsAbstract Factory
Strategy
Prototype
Difficulty LevelMedium
Implementations

Definition

Factory pattern is one of the most popular and commonly used patterns. When we don’t know what type of object is going to be generated then we use the Factory pattern to create objects based on some criteria.

Say, you have a few same types of classes and in your use case those classes can be used anytime anywhere, and you don’t want to restrict the usage of those classes by directly using a new operator, then factory pattern comes into play.

Factory pattern prevents class instantiation in the code directly, instead, it lets a factory class generate the desired item classes.

There are 2 variations of Factory pattern implementation.

  1. Simple Factory Implementation
  2. Factory Method Implementation

Check the implementations below.

Factory Implementation

A simple Factory pattern implementation has 3 elements.

  1. Item Interface: an interface that ensures the type of the Item Concrete classes.
  2. Item Concrete Classes: classes that implement the Item Interface. This implementation will be as per your requirement.
  3. Factory Class: a class that implements a function, which will return instances of Item Concrete classes based on some criteria.

Follow the steps below to implement the factory pattern.

  1. Create an interface that will be used to ensure the same type for the concrete item classes.
  2. Create concrete item classes, and implement the interface. Write the definition of the required functions. This implementation will be as per your requirement.
  3. Create a factory class. create a function that accepts a param to identify which object to return and the return type of the function will be of the Item interface.
  4. In the function return instance of the Item class based on some condition.
  5. In the client create an instance of the factory class.
  6. Call the factory class function to get instances of Item classes.
  7. Now the instance of the Item class.

Let’s take a look at examples.

Factory Example

Let’s take the example of a transport system.

General Interface for Item Classes

interface Transport

   start()

   stop()

   repair()

end interface

Concrete Item Classes

// Bike class

class Bike implements Transport

    function start()
        print("Bike started")
    end function

    function stop()
        print("Bike Stopped")
    end function

    function repair()
        print("Bike Repair")
    end function

end class


// Car class

class Car implements Transport
    
    function start() 
        print("Car started")
    end function

    function stop()
        print("Car Stopped")
    end function

    function repair()
        print("Car Repair")
    end function

end class


// Plane class

class Plane implements Transport

    function start()
        print("Plane started")
    end function

    function stop()
        print("Plane Stopped")
    end function

    function repair()
        print("Plane Repair")
    end function

end class

Factory Class

class TransportFactory

    function getTransport(type: String): Transport
        if (type == "bike")
            return new Bike()
        end if

        if (type == "car")
            return new Car()
        end if

        if (type == "plane")
            return new Plane()
        end if

        return null
    end function

end class

Demo

var transportFactory: TransportFactory = new TransportFactory()

var transport1: Transport = transportFactory.getTransport("bike")
transport1.start()

var transport2: Transport = transportFactory.getTransport("car")
transport2.start()

var transport3: Transport = transportFactory.getTransport("plane")
transport3.start()

Output

Bike started
Car started
Plane started

Factory Method Implementation

Factory method comes into play when you want to move the creation of object parts to different factory sub-classes.

A Factory Method implementation has 4 elements.

  1. Item Interface: interface to ensure the same type of Item Concrete classes.
  2. Item Concrete Classes: concrete classes that implement the Item interface. These implementations will be as per the requirement, there is no strict rule for this implementation.
  3. Factory Abstract Class: abstract class that declares a function to get Item Concrete class instance from Factory Sub-Classes. There can be other functions for using the instance.
  4. Factory Sub-Classes: implement the Factory and returns instance based on some criteria.

Let’s take a look at an example.

Factory Method Example

Let’s take the example of a transport system.

General Interface for Item Classes

interface Transport

   start()

   stop()

   repair()

end interface

Road Transport Concrete Item Classes

// Bus class

class Bus implements Transport

    function start()
        print("Bus started")
    end function

    function stop()
        print("Bus Stopped")
    end function

    function repair()
        print("Bus Repair")
    end function

end class


// Bike class

class Bike implements Transport

    function start()
        print("Bike started")
    end function

    function stop()
        print("Bike Stopped")
    end function

    function repair()
        print("Bike Repair")
    end function

end class


// Car class

class Car implements Transport
    
    function start() 
        print("Car started")
    end function

    function stop()
        print("Car Stopped")
    end function

    function repair()
        print("Car Repair")
    end function

end class

Air Transport Concrete Item Classes

// Plane class

class Plane implements Transport

    function start()
        print("Plane started")
    end function

    function stop()
        print("Plane Stopped")
    end function

    function repair()
        print("Plane Repair")
    end function

end class


// Helicopter class

class Helicopter implements Transport

    function start()
        print("Helicopter started")
    end function

    function stop()
        print("Helicopter Stopped")
    end function

    function repair()
        print("Helicopter Repair")
    end function

end class

Factory Classes

// Transport Factory abstract class

abstract class TransportFactory

    function operateTransport(String name)
       var transport: Transport = getTransport(name)

        transport.start()
        transport.stop()
    end function

    function repairTransport(name: String)
        Transport transport = getTransport(name)

        transport.repair()
    end function

    abstract function getTransport(name: String): Transport

end class


// Road transport factory

class RoadTransportFactory extends TransportFactory

   function getTransport(name: String): Transport
        if (name == "car")
            return new Car()
        end if

        if (name == "bike")
            return new Bike()
        end if

        if (name == "bus") 
            return new Bus()
        end if

        return null
    end function

end class


// Air transport factory

class AirTransportFactory extends TransportFactory
    
    function getTransport(name: String): Transport
        if (name == "plane") 
            return new Plane()
        end if

        if (name == "helicopter") 
            return new Helicopter()
        end if

        return null
    end function

end class

Demo

var roadTransportFactory: TransportFactory = new RoadTransportFactory()
var airTransportFactory: TransportFactory = new AirTransportFactory()

roadTransportFactory.operateTransport("bus")

airTransportFactory.operateTransport("helicopter")

roadTransportFactory.repairTransport("bike")

Output

Bus started
Bus Stopped

---------------------------------------

Helicopter started
Helicopter Stopped

---------------------------------------

Bike Repair

Code Implementations

Use the following links to check Factory pattern implementation in specific programming languages.

Leave a Comment