Java原型模式 浅谈Java设计模式之原型模式知识总结

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java原型模式 浅谈Java设计模式之原型模式知识总结

哟哟之名   2021-05-26 我要评论
想了解浅谈Java设计模式之原型模式知识总结的相关内容吗,哟哟之名在本文为您仔细讲解Java原型模式的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java原型模式,Java设计模式,下面大家一起来学习吧。

如何使用?

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

2.Brother类

public class Brother{
	private String name;
}

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.深拷贝写法

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

这是Brother类

public class Brother implements Cloneable{
    private String name;

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

这里是结果演示

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

在这里插入图片描述

可以看到,user1的brother没有受到user2的影响,深拷贝成功!

5.图解深拷贝与浅拷贝

在这里插入图片描述

总结与思考

java中object类的clone()方法为浅拷贝必须实现Cloneable接口如果想要实现深拷贝,则需要重写clone()方法

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们