定义:原型模式就是用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象
它的场景在于要多次频繁的创建相同对象
原型设计模式使用的是深拷贝和浅拷贝知识 如果不懂什么是深拷贝和浅拷贝,可以去找下资料,在这不讲了,我还要面试呢,没时间了,
public class Order implements Cloneable{
private String name;
private int id;
private double money;
public Order(String name, int id, double money) {
this.name = name;
this.id = id;
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
protected Order clone() throws CloneNotSupportedException {
return (Order) super.clone();
}
@Override
public String toString() {
return "Order{" +
"name='" + name + '\'' +
", id=" + id +
", money=" + money +
'}';
}
}
上面的Order中没有使用到引用类型变量,所以就使用了浅拷贝,如果有的话最好使用深拷贝,至于为什么,还是自己去弄懂什么是浅拷贝和深拷贝.他们的区别在哪里
测试类
public class Client {
public static void main(String[] args) {
Order order = new Order("iphone手机",1,5000);
for(int i=0;i<100;i++){
try {
Order cloneOrder = order.clone();
System.out.println("cloneOrder="+cloneOrder);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
}
突然想起来,创建对象有四种方式 分别是new 克隆 序列化和反序列化 反射
克隆破坏单例设计模式
public class Singleton implements Cloneable {
private String name;
private int id;
private Singleton(){}
private static class Holder{
private static final Singleton holder = new Singleton();
}
public static Singleton getInstance(){
return Holder.holder;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
测试类
public class Test {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
try {
Method method = singleton.getClass().getDeclaredMethod("clone");
method.setAccessible(true);
Singleton cloneSingleton = (Singleton) method.invoke(singleton,null);
System.out.println("原始单例:"+singleton);
System.out.println("克隆后的单例:"+cloneSingleton);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
log:
原始单例:com.kd.principle.protoType.Singleton@511d50c0
克隆后的单例:com.kd.principle.protoType.Singleton@60e53b93
发现克隆后的对象和原始对象并不是一个对象,这样就违背了单例模式的定义,防止克隆破坏单例模式
第一:不要实现Cloneable接口
第二:如果真要实现Cloneable接口的情况下,clone 方法返回的是
@Override
protected Object clone() throws CloneNotSupportedException {
return Holder.singleton;
}