Design Pattern (Part 02)— Factory Method Pattern

Photo by ekicousch on Unsplash

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern

  • It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class so that it will work with any classes that implement that interface or that extend that abstract class.

Factory Design Pattern Examples in JDK

  1. valueOf() method in wrapper classes like Boolean, Integer etc.

Usage of Factory Design Pattern

  • When a class wants that its sub-classes specify the objects to be created.
  • When the parent classes choose the creation of objects to its sub-classes.

Usage

Case study

“Asoft Technologies” is an Computer Educational Institute located in Colombo, SriLanka. Asoft Technologies offering 3 types of short-term Diploma level programs for after ordinary level school students. Every students can follow a single diploma course at a course duration time. Below in this application we are going to create some diploma level objects with rewuired subject based on the each diploma levels.

Diploma Level Programs and Subjects

  1. Knowledge Level — Internet, Web Design
  2. Professional Level — Graphics designing, paint

Now let’s try to find a solution. we need to identify the key elements and classes of the problem.

Step 01

Leaning Class Code
MicrosoftOffice(Subject) Class code
Web Design(Subject) Class code
Graphic Design(Subject) Class code
Internet(Subject) Class code
Paint(Subject) Class code

Step 02

Now we need to create an abstract diploma class. This class will be extended by the Diploma Level classes(Basic Level, Knowledge Level, and Professional Level). This class also contains a method to create the relevant courses called “createCourse()” that will be implemented by the subclasses.

Note: ArrayList is used to store the relevant subject objects created by a particular sub-class.

Diploma Class Code

Step 03

Diploma Basic Level code
Diploma Knowledge Level code
Diploma Professional Level code

Step 04

Course Package code
Package Code Using enum

This package code using for the switch case.

Step 05

Main class code

Output:

Finally, the outcome is showing as based on the Diploma level which we were entered.

Software Engineer at Virtusa (Pvt) Ltd.