作用:将实例的生成交给子类
用Template Method模式来构建生成实例的工厂,这就是Factory Method模式。
在Factory Method中,父类决定实例的生成方式,但并不决定所要生成的具体的类,具体的处理全部交给子类去负责
UML类图:
Product类:
public abstract class Product { public abstract void use(); }
use方法的实现交给Product的子类
Factory类:
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类:
public class IDCard extends Product { private String owner; IDCard(String owner) { this.owner = owner; } public void use() { System.out.println("use it."); } public String getOwner() { return owner; } }
IDCardFactory类:
public class IDCardFactory extends Factory { private List owners = new ArrayList(); protected Product createProduct(String owner) { return new IDCard(owner); } protected void registerProduct(Product product) { owner.add(((IDCard)product).getOwner()); } public List getOwners() { return owners; } }
Main类:
public class Main { public static void main(String[] argvs) { Factory factory = new IDCardFactory(); Product card1 = factory.create("XXX"); card1.use(); } }
步骤:首先创建对应实例的工厂,然后通过实例的工厂去创建对应实例,此中实例的构造函数是包内,并非public