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();
}
}
}