Factory Method模式
Product.java
定义产品的一个模板,每一个继承Product的类都要实现自己的use方法.
public abstract class Product { public abstract void use(); }
Factory.java
为子类(不同种的工厂)定义一个通用模板方法create(),子类可以个性化地实现createProduct()和registerProduct().
public abstract class Factory { public final Product create(String owner) { Product p = createProduct(owner); registerProduct(p); return p; } protected abstract Product createProduct(String owner); protected abstract void registerProduct(Product product); }
IDCard.java
Product的子类
public class IDCard extends Product { private String owner; IDCard(String owner) { System.out.println("制作" + owner + "的ID卡."); this.owner = owner; } @Override public void use() { System.out.println("使用" + owner + "的ID卡"); } public String getOwner() { return owner; } }
IDCardFactory.java
public class IDCardFactory extends Factory { private List owners = new ArrayList(); @Override protected Product createProduct(String owner) { return new IDCard(owner); } @Override protected void registerProduct(Product product) { owners.add(((IDCard) product).getOwner()); } public List getOwners() { return owners; } }
Main.java
测试类
public class Main { public static void main(String[] args) { Factory factory = new IDCardFactory(); Product card1 = factory.create("kristin"); Product card2 = factory.create("John"); Product card3 = factory.create("Marry"); card1.use(); card2.use(); card3.use(); } }
运行结果: