Factory Design Pattern

Beginner

2019-03-04

What is Factory Design Pattern ?

Factory design pattern is a creational design patterns, which is used to create new objects and dependencies while hiding the creating logic.

It's one of the most used design patterns.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Ever went to a restaurant and asked for a burger sandwich. then after 15 minutes the waiter came with the sandwich with all its ingredients inside.

You wasn't involved in preparing these ingredients nor worrying about how much is needed for the best taste.

This is an example of factory design pattern, where you ask a factory to create an object (sandwich) for you without bothering with the details of making this object.

All what you worry about is how to receive this object back when it's created.


What problem does the factory design pattern solve ?

Let's continue with our sandwich example.

Imagine you were in charge of preparing the sandwich ingredients yourself. What you would do is something like this :




This for sure not the best way to create a sandwich, especially when you have to repeat this block each time you want to make a new sandwich.

a solution to this problem is to put this logic inside a factory class and only call the factory sandwich creation method when you need a new sandwich.




Real application examples

  • Factory methods should be considered as an alternative to constructors - mostly when constructors aren't expressive enough, ie.

  • is not as expressive as :


Factory design pattern C# example

Now let's create a C# factory example. the example is about a factory which create a shape object. This shape can be a circle, rectangle or a square

The UML Diagram for the factory design pattern is as follows.

Our factory class will create an object that implements "shape" interface.

the C# code for the example :


  • Each shape implements a well defined interface called "Shape" which has a draw method.
  • The "Factory" interface provides a unified way for contacting with concrete factories.
  • "ConcreteFactory" class implements the "Factory" interface and the "Create" method.
  • The Create method takes in the shape type as a parameter to decide which shape to create.
  • In the main method we can add all these into a single list of shapes and loop through them to draw each one separately.