设计模式:原型模式

本文详细介绍了Java中的对象拷贝,包括浅拷贝和深拷贝的概念。通过实例展示了如何实现深拷贝,以确保拷贝后的对象与原对象相互独立,不受彼此修改的影响。讨论了Object类的clone()方法在浅拷贝中的作用,并指出实现深拷贝需要重写clone()方法并递归处理内部对象。
摘要由CSDN通过智能技术生成

一、解决什么问题?

  1. 用于创建重复的对象,同时又能保证性能。

二、如何使用?

  1. 首先定义一个User类,它必须实现了Cloneable接口,重写了clone()方法。
public class User implements Cloneable {
    private String name;
    private int age;
    private Brother brother;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
  1. Brother类
public class Brother{
	private String name;
}
  1. 应用演示类
public class PrototypeDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        User user1 = new User();
        user1.setName("秋红叶");
        user1.setAge(20);
        Brother brother1 = new Brother();
        brother1.setName("七夜圣君");
        user1.setBrother(brother1);
        // 我们从克隆对象user2中修改brother,看看是否会影响user1的brother
        User user2 = (User) user1.clone();
        user2.setName("燕赤霞");
        Brother brother2 = user2.getBrother();
        brother2.setName("唐钰小宝");
        System.out.println(user1);
        System.out.println(user2);
        System.out.println(user1.getBrother() == user2.getBrother());
    }
}

在这里插入图片描述

  1. 深拷贝写法
    4.1 这是User类
public class User implements Cloneable {
    private String name;
    private int age;
    private Brother brother;

	/**
	* 主要就是看这个重写的方法,需要将brother也进行clone
	*/
    @Override
    protected Object clone() throws CloneNotSupportedException {
        User user = (User) super.clone();
        user.brother = (Brother) this.brother.clone();
        return user;
    }
}

4.2 这是Brother类

public class Brother implements Cloneable{
    private String name;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

4.3 这里是结果演示

public class PrototypeDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        User user1 = new User();
        user1.setName("秋红叶");
        user1.setAge(20);
        Brother brother1 = new Brother();
        brother1.setName("七夜圣君");
        user1.setBrother(brother1);
		// 我们从克隆对象user2中修改brother,看看是否会影响user1的brother
        User user2 = (User) user1.clone();
        user2.setName("燕赤霞");
        Brother brother2 = user2.getBrother();
        brother2.setName("唐钰小宝");
        System.out.println(user1);
        System.out.println(user2);
        System.out.println(user1.getBrother() == user2.getBrother());
    }
}

在这里插入图片描述

4.4 可以看到,user1的brother没有受到user2的影响,深拷贝成功!
4.5 图解深拷贝与浅拷贝
在这里插入图片描述

三、总结与思考

  1. java中object类的clone()方法为浅拷贝
  2. 必须实现Cloneable接口
  3. 如果想要实现深拷贝,则需要重写clone()方法
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值