需求:使用 new 生成实例需要指定类名,在不指定类的情况下生成实例 代码清单: 原型接口 Product: public interface Product extends Cloneable{ void use(String s); Product creatClone();} 实现 UnderlinePen:
需求:使用 new 生成实例需要指定类名,在不指定类的情况下生成实例
代码清单:
原型接口 Product:
public interface Product extends Cloneable{ void use(String s); Product creatClone(); }
实现 UnderlinePen:
public class UnderlinePen implements Product{ private char ulchar; public UnderlinePen(char ulchar){ this.ulchar = ulchar; } @Override public void use(String s) { int length = s.getBytes().length; System.out.println("\""+s+"\""); System.out.print(" "); for(int i=0;i<length;i++){ System.out.print(ulchar); } System.out.println(""); } @Override public Product creatClone() { Product p = null; try{ p=(Product)clone(); }catch (CloneNotSupportedException e){ e.printStackTrace(); } return p; } }
实现:MessageBox
public class MessageBox implements Product{ private char decochar; public MessageBox(char decochar){ this.decochar= decochar; } @Override public void use(String s) { int length = s.getBytes().length; for(int i=0;i<length+4;i++){ System.out.print(decochar); } System.out.println(); System.out.println(decochar+" "+s +" "+decochar); for(int i=0;i<length+4;i++){ System.out.print(decochar); } System.out.println(); } @Override public Product creatClone() { Product p = null; try{ p = (Product)clone(); }catch (CloneNotSupportedException e){ e.printStackTrace(); } return p; } }
Manager 管理类:
public class Manager { private HashMap showcase = new HashMap(); public void register(String name, Product product){ showcase.put(name,product); } public Product create(String productName){ Product p = (Product)showcase.get(productName); return p.creatClone(); } }
测试类:
public class Main { public static void main(String[] args){
Manager manager = new Manager(); UnderlinePen underlinePen = new UnderlinePen(‘.‘); MessageBox messageBox = new MessageBox(‘*‘); MessageBox messageBox1 = new MessageBox(‘/‘); manager.register("Strong",underlinePen); manager.register("Warn",messageBox); manager.register("Flash",messageBox1); Product p1 = manager.create("Strong"); p1.use("Hello,world"); Product p2 = manager.create("Warn"); p2.use("Hello,World"); Product p3 = manager.create("Flash"); p3.use("Hello,world"); } }
结果: