Factory method design pattern

Type: Creational pattern

Description: Factory method design pattern allow you to create an object from one place instead of many places.

By implementing this design pattern, we are ensuring that we are abstracting the logic of object creation at one place only.

Example:

Lets take an example of bank application. Consumer of bank application needs to create an object of different types of bank account like Gold account or Silver account.

To implement this pattern, you need to create a static method and this method will return an instance of a class.

So in this example, GoldAccount and SilverAccount classes will inherit Account class. We have AccountFactory class and it has one static method which is responsible for creating an object of respective account class.

Account
gold
Silver
accountype
accountfactory
consumer

Class diagram:

class diagram

Structure:

structure

Advantages:

1. Code will be maintained and code duplication won’t happen as object creation logic is written at one place.

Leave a Reply

Your email address will not be published. Required fields are marked *