原型模式,是指将一个对象,完整的克隆出一份 实现Cloneable接口,调用clone()方法 应用场景:
/**
* 浅克隆:将对象的值完全拷贝一份,
* 如果属性为引用类型变量,则拷贝属性指向的内存地址
* 实现Cloneable接口
* 重写 clone 方法(不做改造)
*/
public class Student implements Cloneable{
public int id;
public Integer age;
public String name;
public Date createTime;
public Student(int id, Integer age, String name,Date createTime) {
this.id = id;
this.age = age;
this.name = name;
this.createTime = createTime;
}
@Override
public String toString() {
return "Student{" + "id=" + id + ", age=" + age + ", name='" + name + '\'' + ", createTime=" + createTime + '}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws Exception {
Student stu_1 = new Student(1,18,"小红",new Date());
Student stu_2 = (Student) stu_1.clone();
System.out.println(stu_1);
System.out.println(stu_2);
System.out.println("-------修改stu_2的值------");
stu_2.id = 2; //不影响原对象
stu_2.age = 20; //不影响原对象
stu_2.name = "小兰";//不影响原对象
// ------- 影响原对象 -------
stu_2.createTime.setTime(22123156);
System.out.println(stu_1);
System.out.println(stu_2);
}
}
输出结果为:
Student{id=1, age=18, name='小红', createTime=Sun Apr 24 12:39:28 CST 2022}
Student{id=1, age=18, name='小红', createTime=Sun Apr 24 12:39:28 CST 2022}
-------修改stu_2的值------
Student{id=1, age=18, name='小红', createTime=Thu Jan 01 14:08:43 CST 1970}
Student{id=2, age=20, name='小兰', createTime=Thu Jan 01 14:08:43 CST 1970}
/**
* 实现深克隆的方式:
* 1.序列化与反序列化
* 2.改造clone方法
*/
@Override
protected Object clone() throws CloneNotSupportedException {
Student stu = (Student) super.clone();
//将引用类型的变量,也克隆一份
stu.createTime = (Date) this.createTime.clone();
return stu;
}
输出结果为:
Student{id=1, age=18, name='小红', createTime=Sun Apr 24 12:39:28 CST 2022}
Student{id=1, age=18, name='小红', createTime=Sun Apr 24 12:39:28 CST 2022}
-------修改stu_2的值------
Student{id=1, age=18, name='小红', createTime=Sun Apr 24 12:39:28 CST 2022}
Student{id=2, age=20, name='小兰', createTime=Thu Jan 01 14:08:43 CST 1970}
评论
登录后才可以进行评论哦!