1.原型模式的简单介绍
原型模式就是指,对于一个类的对象,获得他的一个副本。副本的属性和方法与该对象相同。
在继续了解之前,还有一些预备知识需要明确。
-
浅复制:对于一个类的对象的简单类型变量,它的副本与其不同。但是对于类类型的变量,副本与原生对象使用的是堆中的同一个。
-
深复制:一个对象的所有类型的变量,都会额外的拷贝一份。
2.原型模式实现
实际上java已经为我们提供了克隆一个对象的方法,并且定义在了所有类的父类Object中,要想使用该方法,类首先需要实现CloneAble接口。
public class Student implements Cloneable{
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student)super.clone();
}
}
public class Client {
public static void main(String[] args) throws Exception{
Student student=new Student();
student.setName("psf");
Student student1 = student.clone();
System.out.println(student.hashCode()==student1.hashCode());
//false
}
上述是典型的浅克隆,Student类中没有自定义的类类型变量。
public class Teacher implements Cloneable{
private Student student;
public void show(){
System.out.println("管理的学生的名字是:"+student.getName());
}
public void setStudent(Student student){
this.student=student;
}
public Student getStudent(){
return student;
}
@Override
protected Teacher clone() throws CloneNotSupportedException {
return (Teacher) super.clone();
}
}
对于Teacher类,有一个Student类型的对象,如果我们单纯的返回super.clone(),那么克隆类的student属性都是同一个。
public class Client {
public static void main(String[] args) throws Exception{
Teacher teacher=new Teacher();
Student student=new Student();
teacher.setStudent(student);
Teacher teacher1 = teacher.clone();
System.out.println(student==teacher1.getStudent());
//true
}
那么如何实现深复制呢。只需要改写clone方法、
protected Teacher clone() throws CloneNotSupportedException {
Teacher t=(Teacher) super.clone();
student=student.clone();
t.setStudent(student);
return t;
}