设计模式-原型模式的深浅拷贝

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值