Abstract Factory Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the abstract factory pattern, a popular creational design pattern.
Tutorial created using:
Windows XP || JDK 1.6.0_10 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)
(Continued from page 1) Animal is an abstract class with the makeSound() abstract method. Subclasses of Animal implement the makeSound() method. Animal.javapackage com.cakes.animals; public abstract class Animal { public abstract String makeSound(); } The Cat class is shown here. Cat.javapackage com.cakes.animals; public class Cat extends Animal { @Override public String makeSound() { return "Meow"; } } The Dog class is shown here. Dog.javapackage com.cakes.animals; public class Dog extends Animal { @Override public String makeSound() { return "Woof"; } } The Snake class is shown here. Snake.javapackage com.cakes.animals; public class Snake extends Animal { @Override public String makeSound() { return "Hiss"; } } The Tyrannosaurus class is shown here. Tyrannosaurus.javapackage com.cakes.animals; public class Tyrannosaurus extends Animal { @Override public String makeSound() { return "Roar"; } } The Demo class contains our main() method. It creates an AbstractFactory object. From the AbstractFactory, we obtain a SpeciesFactory (a ReptileFactory) and get two Animal objects (Tyrannosaurus and Snake) from the SpeciesFactory. After this, we obtain another SpeciesFactory (a MammalFactory) and then obtain two more Animal objects (Dog and Cat). Demo.javapackage com.cakes; import com.cakes.animals.Animal; public class Demo { public static void main(String[] args) { AbstractFactory abstractFactory = new AbstractFactory(); SpeciesFactory speciesFactory1 = abstractFactory.getSpeciesFactory("reptile"); Animal a1 = speciesFactory1.getAnimal("tyrannosaurus"); System.out.println("a1 sound: " + a1.makeSound()); Animal a2 = speciesFactory1.getAnimal("snake"); System.out.println("a2 sound: " + a2.makeSound()); SpeciesFactory speciesFactory2 = abstractFactory.getSpeciesFactory("mammal"); Animal a3 = speciesFactory2.getAnimal("dog"); System.out.println("a3 sound: " + a3.makeSound()); Animal a4 = speciesFactory2.getAnimal("cat"); System.out.println("a4 sound: " + a4.makeSound()); } } Executing the Demo class displays the sounds made by the four Animal objects. The console output is shown here. Console Outputa1 sound: Roar a2 sound: Hiss a3 sound: Woof a4 sound: Meow Notice the use of polymorphism. We obtain different factories via the common SpeciesFactory superclass. We also obtain different animals via the common Animal superclass. Related Tutorials:
|