设计模式示例-原型模式
来源:互联网 发布:重庆市知行卫校 编辑:程序博客网 时间:2024/06/07 11:14
package prototype;import java.util.Hashtable;/** * * 专门用来生产可以克隆的对象,只要实现Product接口的都可以生产 * * @author Administrator * @version [版本号, 2012-10-18] * @see [相关类/方法] * @since [产品/模块版本] */public class Manager{ private Hashtable showcase = new Hashtable(); /** * 注册产品模板的方法 * @param name * @param proto * @see [类、类#方法、类#成员] */ public void register(String name, Product proto) { showcase.put(name, proto); } /** * 根据名称找到对应的产品模板,然后克隆出新产品 * @param protoname * @return * @see [类、类#方法、类#成员] */ public Product create(String protoname) { Product p = (Product)showcase.get(protoname); return p.createClone(); }}
package prototype;/** * * 实现Product接口的具体产品类,可以在类的内部调用clone()方法产生一个新对象 * * @author Administrator * @version [版本号, 2012-10-18] * @see [相关类/方法] * @since [产品/模块版本] */public class MessageBox implements Product{ private char decochar; public MessageBox(char decochar) { this.decochar = decochar; } @Override public Product createClone() { Product product = null; try { product = (Product)clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return product; } @Override public void use(String s) { int length = s.toCharArray().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(""); } }
package prototype;/** * * 产品接口,扩展了Cloneable接口,实现该接口的产品都可以克隆 * * @author Administrator * @version [版本号, 2012-10-17] * @see [相关类/方法] * @since [产品/模块版本] */public interface Product extends Cloneable{ public abstract void use(String s); public abstract Product createClone();}
package prototype;public class TestPrototype{ /** 测试原型模式的主函数 * @param args * @see [类、类#方法、类#成员] */ public static void main(String[] args) { Manager manager = new Manager(); Product p1 = new MessageBox('*'); manager.register("MessageBox", p1); Product clone = manager.create("MessageBox"); clone.use("clone"); p1.use("origin"); } }