一,简单形式的原型模式
package com.wangbiao.test_first;/** * * 简单形式的原型模式 * @author WangBiao * */public abstract class CommonInterface { public abstract CommonInterface clone(); }//第一个真实类class Class_first extends CommonInterface{ @Override public CommonInterface clone() { Class_first c=new Class_first(); return c; } }//第二个真实类class Class_second extends CommonInterface{ @Override public CommonInterface clone() { Class_second c=new Class_second(); return c; } }class Main_Test{ public static void main(String[] args) { CommonInterface common=new Class_second(); CommonInterface common_clone=common.clone(); }}
二,登记形式的原型模式
package com.wangbiao.test_second;import java.util.HashMap;/** * * 登记类型的原型模式 * * @author WangBiao * */public abstract class CommonInterface { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public abstract CommonInterface clone();}// 第一个真实类class Class_first extends CommonInterface { @Override public CommonInterface clone() { Class_first c = new Class_first(); c.setName(this.getName()); return c; }}// 第二个真实类class Class_second extends CommonInterface { @Override public CommonInterface clone() { Class_second c = new Class_second(); c.setName(this.getName()); return c; }}class ProtoTypeManagement { private static HashMapmap = new HashMap (); private ProtoTypeManagement() { } public synchronized static void addProtoType(String name, CommonInterface c) { map.put(name, c); } public synchronized static void removeProtoType(String name) { map.remove(name); } public synchronized static CommonInterface getProtoType(String name) throws Exception { if (!map.containsKey(name)) { // 报异常或者其他操作 System.out.println("没有这个原型模型"); throw new Exception("没有这个原型模型"); } CommonInterface portoType = map.get(name); return portoType; }}class Main_Test { public static void main(String[] args) throws Exception { CommonInterface common = new Class_second(); common.setName("test"); System.out.println(common.getName()); ProtoTypeManagement.addProtoType("P1", common); CommonInterface common_clone_first = ProtoTypeManagement.getProtoType("P1").clone(); System.out.println(common_clone_first.getName()); //动态改变原型对象 CommonInterface temp = new Class_second(); temp.setName("test_again"); ProtoTypeManagement.addProtoType("P1", temp); CommonInterface common_clone_second=ProtoTypeManagement.getProtoType("P1").clone(); System.out.println(common_clone_second.getName()); //删除圆形对象 ProtoTypeManagement.removeProtoType("P1"); CommonInterface common_clone_third=ProtoTypeManagement.getProtoType("P1").clone(); }}