This asset describes the Factory Method Pattern implementation in Java
interface CarPlant {
//This is the factory method
public Car createCar(String str);
}
//This class is one of the 'Concrete Creator' class. It implements the CarPlant interface.
class CarAPlant implements CarPlant{
//This method returns the object of Car type
public Car createCar(String str){
if(str.equals("Petrol")){
//returns an object of type CarAPetrol
return new CarAPetrol();
}else{
//returns an object of type CarADiesel
return new CarADiesel();
}
}
}
//This class is one of the 'Concrete Creator' class. It implements the CarPlant interface.
class CarBPlant implements CarPlant {
//This method returns the object of Car type
public Car createCar(String str){
if(str.equals("Petrol")){
//returns an object of type CarBPetrol
return new CarBPetrol();
}else{
//returns an object of type CarADiesel
return new CarBDiesel();
}
}
}
//This is the abstract 'Product' class. All the products must extend this class
abstract class Car {
//Abstract method display.
public abstract void display();
}
class CarAPetrol extends Car{
//Implements the abstract method display() of the superclass Car.
public void display(){
System.out.println("This is a Petrol variant of CarA");
}
}
class CarADiesel extends Car{
//Implements the abstract method display() of the superclass Car.
public void display(){
System.out.println("This is a Diesel variant of CarA");
}
}
class CarBPetrol extends Car{
//Implements the abstract method display() of the superclass Car.
public void display(){
System.out.println("This is a Petrol variant of CarB");
}
}
class CarBDiesel extends Car{
//Implements the abstract method display() of the superclass Car.
public void display(){
System.out.println("This is a Diesel variant of CarB");
}
}
public class FactoryPatternClass {
//This is the 'Creator' Interface which contains the factory method
public static void main(String args[]){
Car car;
CarPlant carAObj = new CarAPlant();
CarPlant carBObj = new CarBPlant();
//car has the reference to the type CarA
car= carAObj.createCar("Diesel");
//Calls the display method of the CarA class
car.display();
//car now has the reference to the type CarB
car= carBObj.createCar("Diesel");
//Calls the display method of the CarB class
car.display();
}
}