A Factory Design Pattern Example

What is a Factory Design Pattern ?

This is a creational design pattern. It encapsulate the object creation logic from the user by creating a logical separation between the object creation and use.

How we will do it ?

We will gather and create a family of classes having almost similar features. Then we will create a factory class to create and return the desired objects.

Let me do it…

We will consider creating documents in this example.

As a first step let us create an interface and call it as iDocument

We will create classes for separate documents and inherit them from iDocument

The individual classes are ready now. They are inherited from the iDocument interface. We will design the factory to deal with the object.

The factory above will return the object based open the request specified. We will consume it to see the uaseg.

Here we have just called the GetDocument() method to get the desired object. As an end user, from usage point of view, we don’t need to bother about the object creation logic. This way it can encapsulate the object creation logic.

The output in the console would look like as in the image below
ConsoleOutput

Advantages

  • Encapsulates the logic behind the object creation
  • Allows to hook the customization, since it is loosely coupled
  • Disadvantages

  • Addition of new class to the family would need to add more cases in the factory
  • Categories: Design Pattern

    1 comment

    Leave a Reply

    %d bloggers like this: