Abstract Factory Design Pattern in Java

Type:  Creational Design Pattern


Summary

Provide an indirect way to create object that abstracts the creation of families of related objects without directly specifying their concrete Classes. The Factory owns the responsibility create objects. Client is not aware of how to create the object.

Details

It is similar to Factory method design pattern. Only difference is that rather than returning instance of Subclasses, Abstract factory method can create object of Subclasses having different inheritance hierarchy. Generally Abstract Factory will return different Factories, which in turn can be used to Objects

Abstract Factory is used when we want to create objects by Clients and control which instance should be returned. It is used in DAO (Data Access Object).


It can be used to design Platform dependent software solution, by providing platform specific implementations.  

Example

We will extend the example of Sales Man and Different types of Car (SUV, Sedan) to have different type of Car's in terms of its engine (Electric, Gasoline). Now rather than giving an option to create instance of concrete Class like SUV and Sedan, we have an Abstract Factory Class which can return Factory for either ElectricCar or GasolineCar.

Class Diagram


Sample Code



// interface for Engine Factory
public interface EngineProvider {

  public Car getSedan();

  public Car getSuv();
}

// electric Car Factory
public class ElectricCarFactory implements EngineProvider {

  @Override
  public Car getSedan() {
    return new ElectricSedan();
  }

  @Override
  public Car getSuv() {
    return new ElectricSUV();
  }
}


//gasoline Car Factory
public class GasolineCarFactory implements EngineProvider{
 
  @Override
  public Car getSedan() {
    return new GasolineSedan();
  }

  @Override
  public Car getSuv() {
    return new GasolineSUV();
  }

}


// Car Factory Class which interacts with Clients
public class CarFactory {

  private static EngineProvider factory;

  public static EngineProvider getProvider(String providerName) {
    switch (providerName) {
      case "ELECTRIC":
        factory = new ElectricCarFactory();
        break;
      case "GASOLINE":
        factory = new GasolineCarFactory();
        break;

    }
    return factory;
  }
}

Github Code 


Advantages

Provide a standard interface by which family of objects can be created
Internally in the Abstract factory we can use other design patterns like Flyweight or Proxy or Prototype pattern as per the need.

Disadvantages

Sometime supporting for new Object type might lead to changing the interface and refactoring the existing implementation.

References

Comments

Popular posts from this blog

Converting Java Map to String

Invoking EJB deployed on a remote machine

Difference between volatile and synchronized