Java Reference
In-Depth Information
Implementing the Abstract Factory in Plain Code
To demonstrate the abstract factory design pattern, this chapter extends the drinks machine
example by adding a factory that produces two different types of drinks machine: basic and
The “families of related or dependent objects” that the abstract factory creates are the coffee
machine and the soft drinks machine. You must create an interface for the factories to implement. In
Listing 6‐8, you create the AbstractDrinksMachineFactory
LISTING 6‐8: Interface for the abstract factory
public interface AbstractDrinksMachineFactory {
public DrinksMachine createCoffeeMachine();
public DrinksMachine createSoftDrinksMachine();
The concrete implementations of this interface are the GourmetDrinksMachineFactory and the
BasicDrinksMachineFactory classes. For brevity, only the GourmetDrinksMachineFactory is
shown in Listing 6‐9.
LISTING 6‐9: Implementation of the AbstractDrinksMachineFactory
public class GourmetDrinksMachineFactory implements AbstractDrinksMachineFactory{
public DrinksMachine createCoffeeMachine() {
return new GourmetCoffeeMachine();
public DrinksMachine createSoftDrinksMachine() {
return new GourmetSoftDrinksMachine();
Each factory implements the abstract factory's create method in a different way and, depending
on which factory is instantiated, a different implementation of a coffee and soft drinks machine is
AbstractDrinksMachineFactory factory = new GourmetDrinksMachineFactory();
DrinksMachine CoffeeMachine = factory.createCoffeeMachine();
This shows a GourmetDrinksMachineFactory being instantiated. Its coffee machine's
creation method is invoked to create the coffee machine object that this implementation requires.
The full code for this implementation is in the Chapter 06 download.
Search WWH ::

Custom Search