Factory method pattern

The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses." Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type of product that will be created. More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects. Factory methods are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework.
1 answer

Factory Method Pattern example in Java

Here is a sample code for the Factory Pattern in Java. Programmer can use the abstract class Toy to create 3 types of toys Pokemon, BabieGirl, SuperMan in runtime without having to explicitly define the type of the Toy in compile time (see the class FactoryMtdDemo)

import java.util.*;

abstract class Toy {
public abstract void play();
public abstract void stopPlay();

public static Toy factoryMtd(String toyName) throws Exception {

if (toyName == "Pokemon")
return new Pokemon();

if (toyName == "BabieGirl")
return new BabieGirl();

if (toyName == "SuperMan")
return new SuperMan();

throw new Exception("No toy called " + toyName );
}
}

class Pokemon extends Toy {
Pokemon() {}

public void play() {
System.out.println("Pokemon : play");
}
public void stopPlay() {
System.out.println("Pokemon : stopPlay");
}
}

class BabieGirl extends Toy {
BabieGirl() {}

public void play() {
System.out.println("BabieGirl : play");
}
public void stopPlay() {
System.out.println("BabieGirl : stopPlay");
}
}

class SuperMan extends Toy {
SuperMan() {}

public void play() {
System.out.println("SuperMan : play");
}
public void stopPlay() {
System.out.println("SuperMan : stopPlay");
}
}

public class FactoryMtdDemo {

public static void main(String args[]) {
String toyNameLst[] = {"BabieGirl", "SuperMan", "Pokemon", "SuperWoman"};
ArrayList toyAryLst = new ArrayList();
try {
for(int i = 0; i < toyNameLst.length; i++) {
toyAryLst.add(Toy.factoryMtd(toyNameLst[i]));
}
}
catch(Exception e) {
System.out.println(e);
}

Iterator iter = toyAryLst.iterator();

Toy toy = null;
while (iter.hasNext()) {
toy = (Toy)iter.next();
toy.play();
toy.stopPlay();
}
}
}

Taggings: