需求:对象的创建由工厂统一创建,会使用到模板模式
代码清单:
工厂:
public abstract class Factory { public abstract Product createProduct(String owner); public abstract void registerProduct(Product product); public final Product create(String owner){ Product p = createProduct(owner); registerProduct(p); return p; } }
产品:
public abstract class Product { public abstract void use(); }
子工厂:
public class IDCardFactory extends Factory{ private List owners = new ArrayList(); @Override public Product createProduct(String owner) { return new IDCard(owner); } @Override public void registerProduct(Product product) { owners.add(((IDCard)product).getOwner()); } public List getOwners(){ return owners; } }
子产品:
public class IDCard extends Product{ private String owner; IDCard(String owner){ this.owner = owner; } @Override public void use() { System.out.println("使用"+owner+"的身份证"); } public String getOwner(){ return owner; } }
测试方法:
public class Main { public static void main(String[] args){ Factory factory = new IDCardFactory(); Product p1 = factory.create("1"); Product p2 = factory.create("2"); Product p3 = factory.create("3"); p1.use(); p2.use(); p3.use(); } }
原文地址:https://www.cnblogs.com/baizhuang/p/10401027.html
时间: 2024-10-13 16:52:01