一.什么是原型模式
原型模式用于创建重复的对象,同时又能保证性能,提供了创建对象的最佳方式。
二.为什么要原型模式
当创建对象的代价比较大时,可以使用原型模式创建对象。因为new一个对象的时间比克隆一个对象的时间要的多。
三.原型模式应该具备的条件
需要一个原型接口,用于创建当前对象的克隆,原型类自己创建自己的克隆对象。
四.原型demo
public class Demo {
public static void testNew(int size) {
long start = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
User t = new User();
}
long end = System.currentTimeMillis();
System.out.println("new的方式创建耗时:" + (end - start));
}
public static void testClone(int size) throws CloneNotSupportedException {
long start = System.currentTimeMillis();
User t = new User();
for (int i = 0; i < size; i++) {
User temp = (User) t.clone();
}
long end = System.currentTimeMillis();
System.o