Tag Archives: Abstract Factory Pattern

Abstract Factory Pattern – Creational Patterns

Download Sample Here

The Abstract Factory pattern is one level of abstraction higher than the factory pattern. You can use this pattern when you want to return one of several related classes of objects, each of which can return several different objects on request. In other words, the Abstract Factory is a factory object that returns one of several factories.

One classic application of the abstract factory is the case where your system needs to support multiple “look-and-feel” user interfaces, such as Windows-9x, Motif or Macintosh. You tell the factory that you want your program to look like Windows and it returns a GUI factory which returns Windows-like objects. Then when you request specific objects such as buttons, check boxes and windows, the GUI factory returns Windows instances of these visual interface components.

In Java 1.2 the pluggable look-and-feel classes accomplish this at the system level so that instances of the visual interface components are returned correctly once the type of look-and-feel is selected by the program. Here we find the name of the current windowing system and then tell the PLAF abstract factory to generate the correct objects for us.

String laf = UIManager.getSystemLookAndFeelClassName();

try {



catch (UnsupportedLookAndFeelException exc){

System.err.println(“UnsupportedL&F: ” + laf);


catch (Exception exc){

System.err.println(“Error loading ” + laf);


This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes.

Let’s understand this pattern with the help of an example given in the sample code. Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for.

The different parts of computer are, say Monitor, RAM and Processor. The different types of computers are PC, Workstation and Server.  So, here we have an abstract base class Computer. This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The specification of Parts will be different for different types of computers. Let’s have a look at the class Parts. And now let’s go to the sub-classes of Computer. They are PC, and Server.

When to use Abstract Factory Pattern?

One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.

Download Sample Here