Java开发中一般情况下通过使用new 关键字创建对象,但是有时也会在“不指定类名的前提下生成实例”的需求: 对象种类繁多,无法将它们整合到一个类中时 需要处理的对象太多,如果
public interface Product extends Cloneable { public abstract void use(); public abstract Product createClone(); }
public class UnderLinePen implements Product { @Override public void use() { System.out.println("使用UnderLinePen"); } @Override public Product createClone() { Product p = null; try { p = (Product) clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return p; } }
public class MessageBox implements Product { @Override public void use() { System.out.println("使用MessageBox"); } @Override public Product createClone() { Product p = null; try { p = (Product) clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return p; } }
public class Manager { private HashMap<String,Object> registerMap = new HashMap<>(); public void register(String className,Product product) { registerMap.put(className,product); } public Product create(String prototypeName) { Product p = (Product) registerMap.get(prototypeName); return p.createClone(); } }
public class Main { public static void main(String[] args) { Manager manager = new Manager(); manager.register("message",new MessageBox()); manager.register("underLine",new UnderLinePen()); Product message = manager.create("message"); message.use(); Product underLine = manager.create("underLine"); underLine.use(); } }结果: 使用MessageBox 使用UnderLinePen