Tuesday, September 9, 2014
Abstact Factory
Abstract Factory is a creational design pattern that extends the behaviour of basic Factory. It is a Factory of Factories.
Abstract Factory is defined as an interface for creating families of related or dependent objects without specifying their concrete classes.
Here, Vehicle Factory works as an Abstract Factory which creates a type of Vehicle. Vehicle itself represents a Factory that creates a type of Engine. Creates an Engine and Vehicle type are abstracted from implementation.
public interface Engine {
void start();
}
public class CarEngine implements Engine {
@Override
public void start() {
System.out.println("Car Engine starts...");
}
}
public class BusEngine implements Engine {
@Override
public void start() {
System.out.println("Bus Engine starts...");
}
}
public class NoEngine implements Engine {
@Override
public void start() {
System.out.println("No Engine to start...");
}
}
public interface Vehicle {
Engine getEngine();
}
public class Car implements Vehicle {
@Override
public Engine getEngine() {
return new CarEngine();
}
}
public class Bus implements Vehicle {
@Override
public Engine getEngine() {
return new BusEngine();
}
}
public class NoVehicle implements Vehicle {
@Override
public Engine getEngine() {
return new NoEngine();
}
}
public class VehicleFactory {
public static Vehicle createVehicle(String vehicleType){
if("Car".equalsIgnoreCase(vehicleType)){
return new Car();
}
else if("Bus".equalsIgnoreCase(vehicleType)){
return new Bus();
}
else{
return new NoVehicle();
}
}
}
public class AbstractFactoryUser {
public static void main(String[] args) {
Vehicle vehicle = VehicleFactory.createVehicle("car");
Engine engine = vehicle.getEngine();
engine.start(); //Output: Car Engine starts...
Vehicle vehicle2 = VehicleFactory.createVehicle("bus");
Engine engine2 = vehicle2.getEngine();
engine2.start(); //Output: Bus Engine starts...
Vehicle vehicle3 = VehicleFactory.createVehicle("bike");
Engine engine3 = vehicle3.getEngine();
engine3.start(); //Output: No Engine to start...
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment