package com.zjh.designmodel.PrototypeModel;
/*
原型模型:
首先有两个基本点:
拷贝都是对于对象的成员变量来说的
1、浅拷贝对于浅拷贝 在浅拷贝对象时,成员变量的基本数据类型时会直接进行拷贝重新创建一个地址
,浅拷贝对象时只会拷贝他的地址,也就是对对象的引用
2.深拷贝对象时,基本数据类型与对象都会直接创建新地址
*/
public class PrototypeModel {
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student("小明",15);
Object c=student.clone();
Student cloneStudent =(Student) student.clone();
/*true*/ System.out.println(student.getName()== cloneStudent.getName());//比较地址 String的地址是一样的
/*true*/ System.out.println(student.getAge()== cloneStudent.getAge());
//虽然返回true但他们其实不是一个地址;==比较基本数据类型的是值.比较引用类型也就是对象是地址
/*false*/ System.out.println(student==cloneStudent);
/*false*/ System.out.println(student==c);
//上面两个虽然是false但其实指向同一个地址因为我们都用了一个变量名去存储他 也是一个新地址 新地址里面雀指向原来的地址 (套娃)
/*true*/ System.out.println(c.getClass()==student.getClass());
/*true*/ System.out.println(cloneStudent.getClass()==student.getClass());
//java的getClass方法获得的是对象的地址而student的地址就是本身不再指向别的地址,
//c与cloneStudent的地址首先访问他们的存储地址的变量地址然后再指向原来的地址所以是true
//由运行结果来看java的克隆方法是浅拷贝
/*true*/ System.out.println(student.getAgec()== cloneStudent.getAgec());
//虽然返回true但他们其实不是一个地址;==比较基本数据类型的是值.比较引用类型也就是对象是地址
}
}
class Student implements Cloneable {
//在java中Object类型已经内置了Cloneable方法是一个protect类型,我们需要实现接口才能重写
private String name;
private Integer age;
private int agec;
public int getAgec() {
return agec;
}
public void setAgec(int agec) {
this.agec = agec;
}
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// return super.clone();浅拷贝
/*改造深拷贝*/
Student studentC=(Student) super.clone();//先把他的模板考出来把对象成员变量地址改了
studentC.name=new String(name);
studentC.age=new Integer(age);
return studentC;
}
}
设计模式-原型模式的深浅拷贝
最新推荐文章于 2024-04-25 21:06:21 发布