原型模式介绍
原型模式的定义是:
通过给出一个原型对象来指明所有创建的对象的类型,然后用复制这个原型对象的办法创建出更多同类型的对象
也就是说,当我们要创建若干个属性相差不多的对象时,不必每次都去new对象,而可以先创建一个原型,然后用这个原型去克隆出新对象,新对象的属性可以按需修改。
原型模式的写法
原型模式的写法很简单,但是要区分注意是浅拷贝还是深拷贝。
下面展示深拷贝的写法:
要克隆的类型Student,其中有一个属性是Teacher
@Data
@AllArgsConstructor
public class Teacher implements Cloneable{
private String name;
public Teacher clone() throws CloneNotSupportedException {
return (Teacher)super.clone();
}
}
@Data
@AllArgsConstructor
public class Student implements Cloneable{
private String name;
private Teacher teacher;
@Override
public Student clone() throws CloneNotSupportedException {
Student obj = (Student)super.clone();
obj.teacher = teacher.clone();
return obj;
}
}
使用原型克隆创建对象
public static void main(String[] args) throws CloneNotSupportedException {
Student prototypeStudent = new Student("XXX同学",new Teacher("XXX老师"));
List<Student> students = new ArrayList<Student>();
//使用原型克隆对象
for(int i = 0; i < 10; ++i) {
Student student = prototypeStudent.clone();
students.add(student);
}
}
如果Student的属性中有多个属性是引用类型,那么我们继续使用CLoneable接口的写法,就很费功夫,所以可以使用序列化的方式,来实现对象的深拷贝。