Factory Pattern

Taylan Can Hardal
2 min readApr 14, 2022

Hey everyone. In this article, I am going to talk about Factory Patterns. Firstly, we know that patterns are created for a problem. So why was the Factory Pattern created? Where do we use it? Here we go.

Education factory from Pink Floyd

The Factory Pattern is in the Creational Patterns Group. It is currently one of the preferred Design Patterns in the industry. The best way to explain the purpose of Factory Pattern is to give an example. Each pattern is found for a problem, let’s know the problem first.

Imagine you have an E-Commerce site. You are only selling computers here. That’s why your whole project runs on the computer class.

After that, your sales grew and Apple told you it wanted to sell their phones on your site. It’s a great news. So how do you make the class structure? You wrote the project just to sell computers. It’s the time to use Factory Pattern.

First we create an abstract sales class and implement computer and phone classes.

Then, let’s create the Creator class, which will generate objects from these classes, and define our method that will perform the Factory operation.

By the way, we create an Enum named Sales for the products we will sell.

Finally, we create the objects.

Congrats. You fixed your project. You can sell anything, anymore.

In summary:

The program you are writing may also have more than one class similar to each other. They have designed such a pattern so that we do not use the new operator every time when creating such classes, or write code from those classes as if they are independent from each other.

You can find my other Design Pattern articles here :

Referanceses :

bolŞans…

--

--

Taylan Can Hardal

Software Engineer @Turkcell. Savin’ the Earth. Somewhere