Abstract Factory Pattern

Published: 2017-12-29 • Updated: 2019-09-09

Characteristics of Abstract Factory

  • Factory of factories / Collection of factories
  • Common abstract class/Interface
  • Subclasses create the objects

Examples of Abstract Factory

  • DocumentBuilderFactory

Java Implementation

AbstractPhoneFactory.class

public abstract class AbstractPhoneFactory {

  public static OSFactory getFactory(OSType osType){

    switch (osType) {
      case ANDROID:
        return new AndroidFactory();
      case WINDOWS:
        return new WindowsFactory();
      default:
        return null;
    }
  }

}

AbstractFactoryExample.class

public class AbstractFactoryExample {

  public static void main(String[] args) {

    OSFactory factory = AbstractPhoneFactory.getFactory(OSType.ANDROID);
    Phone pixelPhone = factory.create(ManufacturerType.GOOGLE);
    pixelPhone.display();

    OSFactory wfactory = AbstractPhoneFactory.getFactory(OSType.WINDOWS);
    Phone nokiaPhone = wfactory.create(ManufacturerType.MICROSOFT);
    nokiaPhone.display();

  }
}

Disadvantages of Abstract Factory

  • Complex code
  • We realise the need of it while refactoring Facotry Pattern
  • It needs knowledge of Factory Pattern

To access the full working code sample, click here

References

Design Pattern
Share this Post