1、实现
原型模式的克隆分为浅克隆和深克隆。
浅克隆:创建一个新对象,新对象的属性和原来对象完全相同,对于非基本类型属性,仍指向原有属性所指向的对象的内存地址。
深克隆:创建一个新对象,属性中引用的其他对象也会被克隆,不再指向原有对象地址。
Java中的Object类中提供了clone()方法 来实现浅克隆。Cloneable接口上面的类图中的抽象原型类,而实现了Cloneable接口的子实现类就是具体的原型类
package com.jmj.pattern.prototype.demo;
public class Realizetype implements Cloneable{
public Realizetype() {
System.out.println("具体的原型对象创建完成!");
}
@Override
protected Realizetype clone() throws CloneNotSupportedException {
System.out.println("具体原型复制成功!");
return (Realizetype)super.clone();
}
}
package com.jmj.pattern.prototype.demo;
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Realizetype realizetype = new Realizetype();
System.out.println(realizetype);
//没有再次执行无参构造
Realizetype clone = realizetype.clone();
System.out.println(clone);
}
}
package com.jmj.pattern.prototype.test;
import java.io.FilterOutputStream;
public class Citation implements Cloneable{
//三好学生上的姓名
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println(name+"同学:在2020学年第一学期中表现优秀,被评为三好学生。特发此状!");
}
@Override
public Citation clone() throws CloneNotSupportedException {
return (Citation) super.clone();
}
}
package com.jmj.pattern.prototype.test;
public class CitationTest {
public static void main(String[] args) throws CloneNotSupportedException {
//1.创建原型对象
Citation citation = new Citation();
Citation clone = citation.clone();
clone.setName("张三");
citation.setName("李四");
citation.show();
clone.show();
}
}
package com.jmj.pattern.prototype.test11;
import java.io.*;
public class CitationTest {
public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
//1.创建原型对象
Citation citation = new Citation();
Student student = new Student();
student.setName("张三");
citation.setStudent(student);
ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream("src/main/resources/static/b.txt"));
oos.writeObject(citation);
oos.close();
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("src/main/resources/static/b.txt"));
Citation o = (Citation) ois.readObject();
ois.close();
o.getStudent().setName("李四");
citation.show();
o.show();
}
}
总结:浅克隆 实现Cloneable接口 重写clone方法 。
深克隆 用序列化和反序列化实现深克隆。