Wednesday, May 25, 2016

Abstract Factory Design Pattern tutorial example java

Abstract Factory is a factory object that returns one of several factories.Modularization is a big issue in today's programming.Programmers are trying to avoid the idea of adding source code to existing classes in order to make  them support encapsulation.This pattern is one level of abstraction higher than factory method pattern.
Also,Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

When to use Abstract Factory Design Pattern:
This pattern, isolates the concrete classes that are generated which means the names of actual implementing classes are not needed to be known at the client side.

Example: 
public abstract class Car{
public Parts getWheels();
public Parts getBody();
}
public class Parts{
public String specification;
public Parts(String spec){
this.specification=spec;
}
public String getSpecification(){
return specification;
}
}
public class Audi extends Car
{
  public Parts getWheel(){ return new Parts("Audi Wheels");}
  public Parts getBody(){ return new parts("Body of Audi");}
}
public class BMW extends Car
{
  public Parts getWheel(){ return new Parts("BMW Wheels");}
  public Parts getBody(){ return new parts("Body of BMW");}
}
public class CarType{
private Car car;
public static void main(String args[])
{
  CarType type=new CarType();
  Car car =type.getCar("Audi");
  System.out.println("Audi Wheels:" + car.getWheels().getSpecification());
System.out.println("Audi Body:" + car.getBody.getSpecification());
}

public Car getCar(String carType)
{
 if(carType.equals("Audi"))
 {
  car= new Audi();
 }
else if(cartType.equals("BMW))
{
 car= new BMW();
  
}
  return car;
}

}

No comments: