Saturday, November 22, 2014

Abstract Factory - Simple tutorial with an example in Java

    In Factory Method pattern we used a method called factory to create objects.

The concept of Abstract Factory Pattern is having a Factory Class which creates other factories according to the information given. If you remember the Factory Method tutorial you had a Vehicle interface and multiple classes which implement it. You had a factory called VehicleFactory which constructs the correct type of vehicle instance(car bus or van).
This pattern also belongs to the creational patterns group.

The difference in Abstract Factory Pattern is instead of having one VehicleFactory you have multiple factories such as WaterVehicleFactory and LandVehicleFactory ana there is another class which creates the correct factory for you.

See below example.

This is the Vehicle interface.
public interface Vehicle {
}

Below four classes implement above interface.

public class Bus implements Vehicle {
}
public class Car implements Vehicle {
}
public class Ship implements Vehicle {
}
public class Boat implements Vehicle {
}

We can categorize above four classes in to two groups, Land Vehicles and Sea Vehicles. So similarly we can have two factories to create them such as LandVehicleFactory and SeaVehicleFactory.
First we create an super abstract factory class or an interface (AbstractVehicleFactory) and extend LandVehicleFactory and SeaVehicleFactory classes from it as below.


public interface AbstractVehicleFactory {
public Vehicle getVehicle(String size);
}

public class LandVehicleFactory implements AbstractVehicleFactory {
public Vehicle getVehicle(String size) {
if ("large".equals(size)) {
return new Bus();
} else {
return new Car();
}
}
}

public class SeaVehicleFactory implements AbstractVehicleFactory {
public Vehicle getVehicle(String size) {
if("large".equals(size)) {
return new Ship();
} else {
return new Boat();
}
}
}

Finally you need a separate class which is responsible to create and return the correct factory according to the requirement.


public class FactoryCreator {
public static AbstractVehicleFactory getFactory(String terrainType) {
if("sea".equals(terrainType)) {
return new SeaVehicleFactory();
} else if("land".equals(terrainType)) {
return new LandVehicleFactory();
} else {
return null;
}
}
}

I think now you understand this pattern well. You can use below class to test it.


public class Test {
public static void main(String[] args) {
AbstractVehicleFactory factory = FactoryCreator.getFactory("sea");
Vehicle ship = factory.getVehicle("large");
System.out.println(ship.getClass().getSimpleName());
}
}

No comments:

Post a Comment