Factory Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the 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)


Page:    1 2 >

The factory pattern (also known as the factory method pattern) is a creational design pattern. A factory is a JavaSW class that is used to encapsulate object creation code. A factory class instantiates and returns a particular type of object based on data passed to the factory. The different types of objects that are returned from a factory typically are subclasses of a common parent class.

The data passed from the calling code to the factory can be passed either when the factory is created or when the method on the factory is called to create an object. This creational method is often called something such as getInstance or getClass .

As a simple example, let's create an AnimalFactory class that will return an animal object based on some data input. To start, here is an abstract Animal class. The factory will return an instantiated subclass of Animal. Animal has a single abstract method, makeSound().

Animal.java

package com.cakes;

public abstract class Animal {
	public abstract String makeSound();
}

The Dog class is a subclass of Animal. It implements makeSound() to return "Woof".

Dog.java

package com.cakes;

public class Dog extends Animal {

	@Override
	public String makeSound() {
		return "Woof";
	}

}

The Cat class is a subclass of Animal. It implements makeSound() to return "Meow".

Cat.java

package com.cakes;

public class Cat extends Animal {

	@Override
	public String makeSound() {
		return "Meow";
	}

}

(Continued on page 2)

Page:    1 2 >


Related Tutorials: