Abstract factory pattern

An abstract factory pattern is interface for creating a set of related objects, without explicitly specifying their classes. It adds an abstraction layer to the factory pattern and is also called factory of factories.

problems

Suppose we have logic that work with set of related objects. For example, set can be components of computer: keyboard, cpu and etc. But what to do if we want change one set to other set with same types of objects, for example Dell computer to the Apple computer?

advantages

  1. Reduce dependency from concrete classes.
  2. Makes easy to exchange one set of objects to another.
// product abstraction 
class KeyboardA { /*...*/}
class CpuA { /*...*/ }

// concrete products for brands
class KeyboardApple extends KeyboardA { /*...*/ }
class KeyboardDell extends KeyboardA { /*...*/ }
class CpuDell extends CpuA { /*...*/ }
class CpuApple extends CpuA { /*...*/ }

// Abstract factory 
interface ComponentsAbstractFactory{
    KeyboardA createKeyboard();
    CpuA createCpu();
}

// Concrete factory
class AppleComputerFactory implements ComponentsAbstractFactory{
    KeyboardA createKeyboard();
    CpuA createCpu();
}

class DellComputerFactory implements ComponentsAbstractFactory{
    KeyboardA createKeyboard();
    CpuA createCpu();
}
// product abstraction interface Button { void paint(); } // concrete products class WinButton implements Button { @Override public void paint() { System.out.println("WinButton"); } } class OSXButton implements Button { @Override public void paint() { System.out.println("OSXButton"); } } // Abstract factory interface AbstractGUIFactory { public Button createButton(); } // Concrete factory class WinFactory implements GUIFactory { public Button createButton() { return new WinButton(); } } class OSXFactory implements GUIFactory { public Button createButton() { return new OSXButton (); } }