怎么做贷款网站,大连做网站谁家售后好,门户网站系统程序,天元建设集团有限公司第二公司文章目录 原型模式代码示例 原型模式
代码使用#xff1a;spring框架里 bean的作用域 用途#xff0c;以原型为模板#xff0c;源源不断的创建#xff08;克隆 clone#xff09;对象。当直接创建对象的代价比较大时#xff0c;则采用这种模式。
代码示例
public class… 文章目录 原型模式代码示例 原型模式
代码使用spring框架里 bean的作用域 用途以原型为模板源源不断的创建克隆 clone对象。当直接创建对象的代价比较大时则采用这种模式。
代码示例
public class Human implements Cloneable{private int age;private String name;private int sex;public Human(int age, String name, int sex) {this.age age;this.name name;this.sex sex;}Overrideprotected Human clone() {Human human null;try {human (Human) super.clone();} catch (CloneNotSupportedException e) {System.out.println(e);}return human;}
}class PrototypeMap {MapString, Human prototypeMap new HashMap();public PrototypeMap() {// 初始化this.prototypeMap.put(Human, new Human(100, 666, 1));}public Object add(String k, Human v) {this.prototypeMap.put(k, v);return v;}public Human get(String k){Human o this.prototypeMap.get(k);return o null? o:o.clone();}
}
// 验证 原型模式 每次都返回出对象的克隆 且不同 虽然是浅克隆深克隆 可以使用输入输出流 序列化反序列化public static void main(String[] args) {PrototypeMap prototypeMap new PrototypeMap();Human human1 prototypeMap.get(Human);Human human2 prototypeMap.get(Human);System.out.println(human1);System.out.println(System.identityHashCode(human1));System.out.println(human2);System.out.println(System.identityHashCode(human2));}
/*
Human{age100, name666, sex1}
285377351
Human{age100, name666, sex1}
344560770 */