Day 38 after being laid off

Interviews completed = 5 Companies interviewed with = 3 Job offers = 2 Jobs declined = 2 Waiting on responses = 0 Interviews scheduled = 3 Applications entered = 43 Anyone who’s read some of my…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Factory Method Design Pattern in Java

Factory Method Design Pattern is a creational design pattern that states defining an interface or an abstract class for creating an object and let the sub-classes decide which class to instantiate.

Factory Method Design Pattern in Java

This pattern is used when we a super-class and n number of sub-classes and a sub-class should be instantiated based on the input. At this stage, we create a new factory class that takes the responsibility of instantiation of a class from the client.

Factory Method Design Pattern is also known as Factory Design Pattern and as Virtual Constructor.

The main advantage of using Factory Method Design Pattern is that it is making our code more loosely-coupled from my perspective as the implementation is using the interface or abstract class, not the sub-classes.

Let’s look all advantages;

My example is about a vehicle washing mini application. There is an abstract class called Vehicle and concrete classes according to vehicle type that extends the Vehicle class. There is factory class called VehicleFactory.

Every comment is welcome :)

Let’s begin implementing our abstract class, Vehicle.

Then, let’s implementing our sub-classes, Car, Suv, Pickup and Motorcycle.

Now, it is time to implement our factory class, VehicleFactory.

As seen in the factory class implementation, sub-classes are instantiated according to vehicleType parameter.

Finally, let’s see how the factory class is used.

Below is a screenshot after the execution of my example;

Output after the Execution of my Example

Long story short, when a class does not know what sub-classes will be instantiated and when a class wants its sub-classes determine the objects to be instantiated, we can use Factory Method Design Pattern. By doing so, we can maintain the loosely-coupling with encapsulating our sub-classes from implementation.

Add a comment

Related posts:

CDS Exam coaching in Chandigarh

The full form of CDS stands for Combined Defence Services. The CDS Examination is conducted by the UPSC (Union Public Service Commission) for the recruitment of designated officers in the Indian…

The Quickest January of the History and how it went as a teen

Hi guys! I Aditi and I’m 17 years old. Being a teenager a lot of times I just lost in my own world while thinking about my future and these things actually gives me chills. And I constantly have a…

3 Harsh Truths That Will Change The Way You Go About Your Life

Remember the time you fell in front of everybody? Or the time you did a bad thing, and the news got out? Or when something happened to you and people were staring and talking about you? You’d never…