设计模式——原型模式05-浅拷贝

时间:2024-04-08 21:25:06

克隆出对象,其中两者的引用类型属性是同一个对象。

对象信息

/**
 * @author ggbond
 * @date 2024年04月03日 08:38
 */
public class Mankind01 implements Cloneable {
    private  int age;
    private Date birth;

    public Mankind01(int age, Date birth){
        this.age=age;
        this.birth=birth;
    }

    public int getAge() {
        return age;
    }

    public Date getBirth() {
        return birth;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    protected Mankind01 clone() throws CloneNotSupportedException {

        return (Mankind01) super.clone();

    }
}

测试

/**
 * @author ggbond
 * @date 2024年04月03日 08:42
 *
 */
public class test01 {
    public static void main(String[] args) throws Exception {
        Date birth=new Date(2022,4,3);
        int age=25;
        Mankind01 m1=new Mankind01(age,birth);
        Mankind01 m2=m1.clone();
        System.out.println("m1.age:"+m1.getAge()+"  "+"m2.age:"+m2.getAge());
        System.out.println("m1.birth:"+m1.getBirth()+"  "+"m2.birth:"+m2.getBirth());
        System.out.println("-----------");

        age=21; birth.setTime(1232321321L);

        System.out.println(m1.getBirth() == m2.getBirth()); // true
        System.out.println("m1.age:"+m1.getAge()+"  "+"m2.age:"+m2.getAge());
        System.out.println("m1.birth:"+m1.getBirth()+"  "+"m2.birth:"+m2.getBirth());

    }
}

测试结果发现, m1,m2 中的属性 引用类型 Date birth 是指向同一个对象

m1.age:25  m2.age:25
m1.birth:Wed May 03 00:00:00 CST 3922  m2.birth:Wed May 03 00:00:00 CST 3922
-----------
true
m1.age:25  m2.age:25
m1.birth:Thu Jan 15 14:18:41 CST 1970  m2.birth:Thu Jan 15 14:18:41 CST 1970

在这里插入图片描述