程序示例
Main类是测试用类。
//Product类
//product类 public abstract class Product { public abstract void use(); }//Factory类
public abstract class Factory { public final Product create(String string) { Product p = createProduct(owner); registerProduct(p); return p; } protected abstract Product createProduct(String owner); protected abstract void registerProduct(Product product); }//IDCard类
Public class IDCard extends Product { private String owner; IDCard(String owner) { System.out.println("建立"+owner+"的卡"); this.owner = owner; } public void use() { System.out.println("使用"+owner+"的卡"); } public String getOwner() { return owner; } }//IDCardFactory类
public class IDCardFactory extends Factory { private Vector owners = new Vector(); protected Product createProduct(String owner) { return new IDCard(owner); } protected void registerProduct(Product product) { owners.add(((IDCard)product).getOwner()); } public Vector getOwners() { return owners; } }//Main类
public class Main { public static void main(String[] args) { Factory factory = new IDCardFactory(); Product card1 = factory.create("changbin"); Product card2 = factory.create("daniel"); card1.use(); card2.use(); } }