Factory Design Pattern (DP) is used to create an object without exposing the creation logic. It comes under the creational pattern.
To understand how Factory DP works lets take a simple example of "Vehicle".
To get the object of the "Vehicle" we will pass details like (TwoWheeler, FourWheeler) to VehicleFactory and VehicleFactory will return an object of the type "Vehicle" based on the parameter passed.
Overall here is an architecture of our implementation:
Lets see implementation of classes/interface:
Step 1: Vehicle Interface which has prototype method called "speed"
package com.designpattern.factory;
public interface Vehicle {
void speed();
}
To understand how Factory DP works lets take a simple example of "Vehicle".
To get the object of the "Vehicle" we will pass details like (TwoWheeler, FourWheeler) to VehicleFactory and VehicleFactory will return an object of the type "Vehicle" based on the parameter passed.
Overall here is an architecture of our implementation:
Lets see implementation of classes/interface:
Step 1: Vehicle Interface which has prototype method called "speed"
package com.designpattern.factory;
public interface Vehicle {
void speed();
}
Step 2: Concrete implementation of "Vehicle" interface.
package com.designpattern.factory;
public class TwoWheeler implements Vehicle {
@Override
public void speed() {
System.out.println("Hey my max speed is 110km/hr");
}
}
package com.designpattern.factory;
public class FourWheeler implements Vehicle {
@Override
public void speed() {
System.out.println("Hey my max speed is 180km/hr");
}
}
Step 3: VehicleFactory class which actually creates the object of Vehicle based on the "vehicleType"
package com.designpattern.factory;
public class VehicleFactory {
public Vehicle getVehicle(String vehicleType) {
if(null == vehicleType) {
return null;
} else if("TwoWheeler".equalsIgnoreCase(vehicleType)) {
return new TwoWheeler();
} else if("FourWheeler".equalsIgnoreCase(vehicleType)) {
return new FourWheeler();
}
return null;
}
}
Step 4: Demo class which makes use of the "VehicleFactory" class and uses the object returned/created by "VehicleFactory" class
package com.designpattern.factory;
public class Demo {
public static void main (String args[]) {
VehicleFactory vehicleFactory = new VehicleFactory();
Vehicle vehicle1 = vehicleFactory.getVehicle("TwoWheeler");
vehicle1.speed();
Vehicle vehicle2 = vehicleFactory.getVehicle("FourWheeler");
vehicle2.speed();
}
}
Step 5: Check out the output of "Demo" class
Here is the output of "Demo" program:
Hey my max speed is 110km/hr
Hey my max speed is 180km/
Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

No comments:
Post a Comment