原型模式是什么?
利用一个对象做原型,拷贝生成多个相似的对象叫做原型模式。
是创建复杂对象的一种快速高效的方式。
适用场景
代码实现
最简单的原型模式
JDK默认提供了原型模式,java.lang.Cloneable接口就是一个原型模式
实现java.lang.Cloneable 方法,重写clone()方法即可实现原型模式,注意两点:
- clone()方法是java.lang.Object类提供的,每个对象都默认继承了这个方法,且这个方法是native实现

- 如果不实现java.lang.Cloneable 接口,会报错java.lang.CloneNotSupportedException异常
来一个最简单的原型模式代码实现:
/*** 原型模式* 原型类 实现JDK的Cloneable接口即可*/class Prototype implements Cloneable {//具有代表性类型的属性private Integer i;//基本类型private String s;//字符串类型@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}}//测试类public class PrototypeTest {public static void main(String[] args) throws InterruptedException, CloneNotSupportedException {Prototype p1 = new Prototype();Object p2 = p1.clone();System.out.println("p1==p2:" + (p1 == p2));//输出:p1==p2:false}}
实现Cloneable接口并重写clone(),JDK默认就帮我们实现了原型模式,这就是我们常说的“浅拷贝”,只复制基本类型的数据,引用类型的数据只复制了引用的地址,引用的对象并没有复制,在新的对象中修改引用类型的数据会影响原对象中的引用。
- 对于基本类型,拷贝其值
-
浅拷贝-基本类型
基本类型全拷贝,无影响 ```java //具体原型类 class Prototype implements Cloneable {
//具有代表性类型的属性 private Integer i;//基本类型 private String s;//字符串类型
@Override protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
//构造方法 public Prototype(Integer i, String s) {
this.i = i;this.s = s;
}
//—-geter和seter方法 public Integer getI() {
return i;
}
public void setI(Integer i) {
this.i = i;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
//重写toString方法 方便查看对象@Overridepublic String toString() {return "Prototype{" +"i=" + i +", s='" + s + '\'' +'}';}
}
//测试类 public class PrototypeTest { public static void main(String[] args) throws InterruptedException, CloneNotSupportedException { Prototype p1 = new Prototype(1, “对象1”); Prototype p2 = (Prototype) p1.clone();
System.out.println("p1 == p2:" + (p1 == p2));System.out.println("p1:" + p1);System.out.println("p2:" + p2);//输出://p1 == p2:false//p1:Prototype{i=1, s='对象1'}//p2:Prototype{i=1, s='对象1'}}
}
<a name="AsCtP"></a>## 浅拷贝-引用对象在刚才的类的集成上增加一个引用对象 Other```java//具体原型类class Prototype implements Cloneable {//具有代表性类型的属性private Integer i;//基本类型private String s;//字符串类型private Other other;//引用类型@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}//构造方法public Prototype(Integer i, String s, Other other) throws InterruptedException {this.i = i;this.s = s;this.other = other;}//---geter和seter方法public Integer getI() {return i;}public void setI(Integer i) {this.i = i;}public String getS() {return s;}public void setS(String s) {this.s = s;}public Other getOther() {return other;}public void setOther(Other other) {this.other = other;}//重写toString方法 方便查看对象@Overridepublic String toString() {return "Prototype{" +"i=" + i +", s='" + s + '\'' +", other=" + other +'}';}}class Other {private int id;private String name;public Other(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Other{" +"id=" + id +", name='" + name + '\'' +'}';}}//测试类public class PrototypeTest {public static void main(String[] args) throws InterruptedException, CloneNotSupportedException, IOException, ClassNotFoundException {Prototype p1 = new Prototype(1, "对象1", new Other(11, "对象11"));Prototype p2 = (Prototype) p1.clone();Other other1 = p1.getOther();Other other2 = p2.getOther();System.out.println("p1 == p2:" + (p1 == p2));System.out.println(p1);System.out.println(p2);System.out.println("sub1 == sub2:" + (other1 == other2));System.out.println("sub1:" + other1);System.out.println("sub2:" + other2);p1.getOther().setId(3333);System.out.println(p1);System.out.println(p2);//不显示指定clone()方法 则为浅拷贝//输出://p1 == p2:false//Prototype{i=1, s='对象1', other=Other{id=11, name='对象11'}}//Prototype{i=1, s='对象1', other=Other{id=11, name='对象11'}}//sub1 == sub2:true//sub1:Other{id=11, name='对象11'}//sub2:Other{id=11, name='对象11'}//Prototype{i=1, s='对象1', other=Other{id=3333, name='对象11'}}//Prototype{i=1, s='对象1', other=Other{id=3333, name='对象11'}}}}
深拷贝-重写clone()方式
- 所有的类都需要实现Cloneable,并显示指定clone()方法
核心代码
@Overrideprotected Object clone() throws CloneNotSupportedException {Prototype prototype = (Prototype) super.clone();//需要显示指定所有引用对象的clone()方法prototype.other = (Other) other.clone();return prototype;}
```java //具体原型类 class Prototype implements Cloneable {
//具有代表性类型的属性 private Integer i;//基本类型 private String s;//字符串类型 private Other other;//引用类型
@Override protected Object clone() throws CloneNotSupportedException {
Prototype prototype = (Prototype) super.clone();//需要显示指定所有引用对象的clone()方法prototype.other = (Other) other.clone();return prototype;
}
//构造方法 public Prototype(Integer i, String s, Other other) throws InterruptedException {
this.i = i;this.s = s;this.other = other;
}
//—-geter和seter方法 public Integer getI() {
return i;
}
public void setI(Integer i) {
this.i = i;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public Other getOther() {
return other;
}
public void setOther(Other other) {
this.other = other;
}
//重写toString方法 方便查看对象@Overridepublic String toString() {return "Prototype{" +"i=" + i +", s='" + s + '\'' +", other=" + other +'}';}
}
class Other implements Cloneable { private int id; private String name;
@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}public Other(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Other{" +"id=" + id +", name='" + name + '\'' +'}';}
}
//测试类 public class PrototypeTest { public static void main(String[] args) throws InterruptedException, CloneNotSupportedException, IOException, ClassNotFoundException { Prototype p1 = new Prototype(1, “对象1”, new Other(11, “对象11”)); Prototype p2 = (Prototype) p1.clone();
Other other1 = p1.getOther();Other other2 = p2.getOther();System.out.println("p1 == p2:" + (p1 == p2));System.out.println(p1);System.out.println(p2);System.out.println("sub1 == sub2:" + (other1 == other2));System.out.println("sub1:" + other1);System.out.println("sub2:" + other2);p1.getOther().setId(3333);System.out.println(p1);System.out.println(p2);//显示指定clone()方法 则为深拷贝//输出://p1 == p2:false//Prototype{i=1, s='对象1', other=Other{id=11, name='对象11'}}//Prototype{i=1, s='对象1', other=Other{id=11, name='对象11'}}//sub1 == sub2:false//sub1:Other{id=11, name='对象11'}//sub2:Other{id=11, name='对象11'}//Prototype{i=1, s='对象1', other=Other{id=3333, name='对象11'}}//Prototype{i=1, s='对象1', other=Other{id=11, name='对象11'}}}
}
**个人的理解是Java中定义的clone没有深浅之分,都是统一的调用Object的clone方法。为什么会有深克隆的概念?是由于我们在实现的过程中刻意的嵌套了clone方法的调用。也就是说深克隆就是在需要克隆的对象类型的类中全部实现克隆方法。就像是toString方法一样。**<br />总结:<br />1.浅克隆:只复制基本类型的数据,引用类型的数据只复制了引用的地址,引用的对象并没有复制,在新的对象中修改引用类型的数据会影响原对象中的引用。<br />2.深克隆:是在引用类型的类中也实现了clone,是clone的嵌套,复制后的对象与原对象之间完全不会影响。<br />4.使用clone实现的深克隆其实是浅克隆中嵌套了浅克隆,与toString方法类似<br />_<a name="drDHE"></a>## 深拷贝-序列化方式使用对象序列化方式,把一个对象写入内存,然后从内存重写读取,拷贝出另一个对象,也可以实现深拷贝。```java//具体原型类class Prototype implements Serializable {//具有代表性类型的属性private Integer i;//基本类型private String s;//字符串类型private Other other;//引用类型//构造方法public Prototype(Integer i, String s, Other other) {this.i = i;this.s = s;this.other = other;}//---geter和seter方法public Integer getI() {return i;}public void setI(Integer i) {this.i = i;}public String getS() {return s;}public void setS(String s) {this.s = s;}public Other getOther() {return other;}public void setOther(Other other) {this.other = other;}//重写toString方法 方便查看对象@Overridepublic String toString() {return "Prototype{" +"i=" + i +", s='" + s + '\'' +", other=" + other +'}';}}class Other implements Serializable {private int id;private String name;public Other(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Other{" +"id=" + id +", name='" + name + '\'' +'}';}}//测试类public class PrototypeTest {public static void main(String[] args) throws InterruptedException, CloneNotSupportedException, IOException, ClassNotFoundException {//实现深拷贝Prototype p1 = new Prototype(1, "对象1", new Other(11, "对象11"));//将对象写入内存ByteArrayOutputStream bos = new ByteArrayOutputStream();new ObjectOutputStream(bos).writeObject(p1);//从内存读取对象Prototype p2 = (Prototype) new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())).readObject();System.out.println();System.out.println("p1 == p2:" + (p1 == p2));System.out.println(p1);System.out.println(p2);Other other1 = p1.getOther();Other other2 = p2.getOther();System.out.println("sub1 == sub2:" + (other1 == other2));//深拷贝 引用对象也是重新拷贝一个新的对象System.out.println("sub1:" + other1);System.out.println("sub2:" + other2);p1.getOther().setId(3333);System.out.println(p1);System.out.println(p2);//输出://p1 == p2:false//Prototype{i=1, s='对象1', other=Other{id=3333, name='对象11'}}//Prototype{i=1, s='对象1', other=Other{id=11, name='对象11'}}//sub1 == sub2:false//sub1:Other{id=3333, name='对象11'}//sub2:Other{id=11, name='对象11'}//Prototype{i=1, s='对象1', other=Other{id=3333, name='对象11'}}//Prototype{i=1, s='对象1', other=Other{id=11, name='对象11'}}}}
- 所有类都实现Serializable接口,使其可序列化
对象写入内存
ByteArrayOutputStream bos = new ByteArrayOutputStream();new ObjectOutputStream(bos).writeObject(p1);
复制对象的过程就是反序列化的过程
Prototype p2 = (Prototype) new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())).readObject();
深拷贝-耗时测试
深拷贝可以节省时间?做个测试
模拟创建对象的时候耗时操作//模拟创建对象耗时操作try {Thread.sleep(3_000);} catch (InterruptedException e) {e.printStackTrace();}
```java //具体原型类 class Prototype implements Serializable {
//具有代表性类型的属性 private Integer i;//基本类型 private String s;//字符串类型 private Other other;//引用类型
//构造方法public Prototype(Integer i, String s, Other other) {this.i = i;this.s = s;this.other = other;//模拟创建对象耗时操作try {Thread.sleep(3_000);} catch (InterruptedException e) {e.printStackTrace();}}//---geter和seter方法public Integer getI() {return i;}public void setI(Integer i) {this.i = i;}public String getS() {return s;}public void setS(String s) {this.s = s;}public Other getOther() {return other;}public void setOther(Other other) {this.other = other;}//重写toString方法 方便查看对象@Overridepublic String toString() {return "Prototype{" +"i=" + i +", s='" + s + '\'' +", other=" + other +'}';}
}
class Other implements Serializable { private int id; private String name;
public Other(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Other{" +"id=" + id +", name='" + name + '\'' +'}';}
}
//测试类 public class PrototypeTest { public static void main(String[] args) throws InterruptedException, CloneNotSupportedException, IOException, ClassNotFoundException { long start1 = System.currentTimeMillis(); Prototype p1 = new Prototype(1, “对象1”, new Other(11, “对象11”)); long end1 = System.currentTimeMillis(); System.out.println(“new对象耗时:” + (end1 - start1)); //将对象写入内存 ByteArrayOutputStream bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(p1);
//从内存读取对象long start2 = System.currentTimeMillis();Prototype p2 = (Prototype) new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())).readObject();long end2 = System.currentTimeMillis();System.out.println("内存拷贝对象耗时:" + (end2 - start2));}//输出://new对象耗时:3002//内存拷贝对象耗时:35
``` 总结:
1.浅克隆:只复制基本类型的数据,引用类型的数据只复制了引用的地址,引用的对象并没有复制,在新的对象中修改引用类型的数据会影响原对象中的引用。
2.深克隆:是在引用类型的类中也实现了clone,是clone的嵌套,复制后的对象与原对象之间完全不会影响。
3.使用序列化也能完成深复制的功能:对象序列化后写入流中,此时也就不存在引用什么的概念了,再从流中读取,生成新的对象,新对象和原对象之间也是完全互不影响的。
4.使用clone实现的深克隆其实是浅克隆中嵌套了浅克隆,与toString方法类似
