1 /** 
   2  * FactoryMethodPattern Example
   3  */
   4 
   5 import java.util.*;
   6 
   7 abstract class Product {
   8     public abstract void use();
   9 }
  10 
  11 abstract class Factory {
  12     public final Product create(String owner) {
  13         Product p = createProduct(owner);
  14         registerProduct(p);
  15         return p;
  16     }
  17     protected abstract Product createProduct(String owner);
  18     protected abstract void registerProduct(Product product);
  19 }
  20 
  21 class IDCard extends Product {
  22     private String owner;
  23     IDCard(String owner) {
  24         System.out.println(owner+"'s card making");
  25         this.owner = owner;
  26     }
  27     public void use() {
  28         System.out.println(owner+"'s card using");
  29     }
  30     public String getOwner() {
  31         return owner;
  32     }
  33 }
  34 
  35 class IDCardFactory extends Factory {
  36     private Vector owners = new Vector();
  37     protected Product createProduct(String owner) {
  38         return new IDCard(owner);
  39     }
  40     protected void registerProduct(Product product) {
  41         owners.add(((IDCard)product).getOwner());
  42     }
  43     public Vector getOwners() {
  44         return owners;
  45     }
  46 }
  47 
  48 public class FactoryMethodIdCard {
  49     public static void main(String[] args) {
  50         Factory factory = new IDCardFactory();
  51         Product card1 = factory.create("Jane");
  52         Product card2 = factory.create("Bob");
  53         card1.use();
  54         card2.use();
  55     }
  56 }
web biohackers.net