Factory Design Pattern

What is Factory Design Pattern

In the factory design pattern, there is a class that you can think of as a factory. If you want to instantiate a class, you would use the use the factory to help you produce the proper object for you, based on input conditions at run time. In this way, you do not need to know what object is needed before run time to program it into the code. The factory will worry about the details. To illustrate, I’ll continue with the pizza analogy.

 

Some examples:

1. Choosing the correct shape to draw based on what needs to be shown in a game, video, or drawing program.

2. The proper border of windows based on size and content. The borders could be scrollable, change if the window is full screen, or any other combinations of types.

 

What are the functions of each part

Factory:

– The class that produces the product

 

Product class:

– The classes that will be instantiated (produced). It can be shapes, different style borders of a window, or different kinds of pizzas

 

Client:

– The class that will use the factory to produce the desired product. In this example, it will be the main class.

 

Getting into the Code

In this post, I will keep up with the theme of pizza and show a simple example of how to use the factory design pattern. This will be a simple program to show the concepts of the design pattern.

First, I want to have the products (the pizzas) have the same interface. This will keep the products the same so the factory can easily create the product that I want.

 

Interface:

 

 

Products:

 

Factory:

 

Client:

 

Output:

 

Advantages of Factory Design Pattern:

Having the decision making code that will produce the proper object based on user input in a central location is the main advantage to this design pattern. Giving users a choice in which shape to draw, what boarders to make, or any other situations where choosing the proper object is important, it is more difficult to program a loosely coupled code without making a central “factory” of some sort.