AbstractFactoryDesignPattern
AbstractFactoryDesignPattern
book(int distance){
setVehicleType()
setBaseCost()
setVehicleChargesPerUnitDistance()
int cost = calculateCostOfBooking(distance)
print(carType + ", " + distance + ", " + cost + ". ")
MicroCar()
define concrete class MicroCar
setVehicleType() for Car
carType = "Micro"
setBaseCost()
baseCost = 50
setVehicleChargesPerUnitDistance()
chargesPerUnitDistance = 10
PersonalAuto()
setVehicleType()
define concrete class SportsBike
bikeType = "Sports"
for Bike
setBaseCost()
baseCost = 10
setVehicleChargesPerUnitDistance()
chargesPerUnitDistance = 15
define abstract class
6) abstract class AbstractVehicleFactory
AbstractVehicleFactory which
abstract Vehicle getVehicle(String type)
is factory of factory
Abstract Factory Design Pattern
9) class FactoryProvider
static AbstractVehicleFactory getVehicleFactory(String factoryType)
if(factoryType.equalsIgnoreCase("Car"))
return new CarFactory()
else if(factoryType.equalsIgnoreCase("Auto")) define FactoryProvider that
return new AutoFactory() provides required vehicle factory
else if(factoryType.equalsIgnoreCase("Bike"))
return new BikeFactory()
else
return new CarFactory()
Abstract Factory Design Pattern
/*
* Book a Personal Auto for a distance of 10 kms
*/
AbstractVehicleFactory autoFactory = FactoryProvider.getVehicleFactory("Auto")
Vehicle personalAuto = autoFactory.getVehicle("Personal")
personalAuto.book(distance)
Abstract Factory Design Pattern
Advantages
offers loose coupling in the code
supports open close principle since the
code can be easily extended for
supporting new classes
enforces consistent creation of objects
Disadvantages
increased complexity