Hi guys✋,This is day 5 of landing a Job in 30days👩💻.
The factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes the responsibility of the instantiation of a class from the client program to the factory class.
The Factory Pattern is an Interface that defers the creation of the final object to a subclass.
Lets take an example of a Car .
Without Factory
// library class
import java.io.*;
abstract class Car{
public abstract void drive();
}
class MercedesBenz extends Car{
public void drive(){
System.out.println("You are riding Mercedes-Benz");}
}
class RangeRover extends Car {
public void drive(){
System.out.println("You are riding Range Rover"); }
}
// Client Class
class Client {
private Car car;
public Client(int type){
if (type == 1)
car = new RangeRover();
else if (type == 2)
car= new MercedesBenz();
else
car = null;
}
public Car getCar(){
return car;
}
}
//Main program
public class Solution {
public static void main(String[] args) {
Client client = new Client(1);
Car car = client.getCar();
if (car != null) {
car.drive();
}
}
}
Here when new object is created then we have to increase the if statement in the client side .So to avoid we can use factory design pattern.
With factory design pattern
Car Interface
public abstract class Car{
abstract void drive();
}
//Mercedes-Benz class
public class MercedesBenz extends Car{
private MercedesBenz(){}
@Override
void drive(){
System.out.println("You are riding Mercedes-Benz");}
}
//Range Rover class
public class RangeRover extends Car{
private RangeRover(){}
@Override
void drive(){
System.out.println("You are riding Range Rover");}
}
//Car Factory class - Here the factory takes care of creation of object which is abstracted from client.
import java.util.Objects;
public class CarFactory{
public static Car getCar(String type){
if(Objects.equals(Type, "MercedesBenz"))
return new MercedesBenz();
else if (Objects.equals(Type, "RangeRover"))
return new RangeRover();
}
}
//Client Class
public class Main {
public static void main(String[] args) {
Car car = CarFactory.getCar("Range Rover");
car.drive();
}
}
The outline of the factor design method
Problem solved today
Happy Coding!!!!😃