Factory Method Design Pattern

Tharaka Dissanayake
2 min readJul 1, 2022

--

It is a creational design pattern. In the factory method pattern, usually, parameters are passed to get the object. This method mainly focuses on getting the object instead of the procedure for creating the object. That means the object creation will be hidden from the user. The factory method design pattern lets to subclass to get an object it wants.

Example

Think, If you want to see a description of the mobile operating system. Then you need to create the object to get details about the operating system. The main code will be polluted if you add a new OS or want to change the object creation steps. Using the factory method, object creation can be separated into another class. So updating the application will be easy, and the factory method will not pollute the main code base.

01- Create an interface for Operating systems.

Interface for creating operating systems

02- Implements Android class with Operating System interface

Android class

03- Implements Windows class with Operating System interface

Windows class

04- Creating the factory method class to get the operating system instance.

Factory method class.

05- Main method

Main method

06- Compiled results

Final output

--

--

Tharaka Dissanayake
Tharaka Dissanayake

No responses yet