首页 > 其他 > 详细

原型模式

时间:2021-07-30 22:51:23      阅读:31      评论:0      收藏:0      [点我收藏+]

原型模式

深拷贝 浅拷贝

public class CloneTest implements Cloneable{
    String name;

    public CloneTest(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode())+"CloneTest{" +
                "name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }

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

public class CloneObject implements Cloneable{
     String name;
     Integer age;
    CloneTest cloneTest;

    public CloneObject(String name, Integer age, CloneTest cloneTest) {
        this.name = name;
        this.age = age;
        this.cloneTest = cloneTest;
    }

    @Override
    public String toString() {
        return "CloneObject{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ", cloneTest=" + cloneTest +
                ‘}‘;
    }
   //深拷贝实现
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //方式一
        CloneObject cloneObject = (CloneObject)super.clone();
        CloneTest cloneTest = this.cloneTest.clone();
        cloneObject.cloneTest=cloneTest;
        return cloneObject;
        //方式二 使用oos ObjectOutputStream()
    }

    public static void main(String[] args) {
        CloneTest cloneTest =new CloneTest("test");
        CloneObject cloneObject = new CloneObject("花花",12,cloneTest);
        try {
            Object clone = cloneObject.clone();

            System.out.println(cloneObject);
            //默认是浅拷贝
            //CloneTest cloneTest;为同一个地址 改变 cloneTest内参数 导致clone也会被改变
            cloneObject.cloneTest.name="hh";

            System.out.println(clone);
//            CloneObject{name=‘花花‘, age=12, cloneTest=com.build.CloneTest@4554617cCloneTest{name=‘test‘}}
//            CloneObject{name=‘花花‘, age=12, cloneTest=com.build.CloneTest@4554617cCloneTest{name=‘hh‘}}
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

原型模式

原文:https://www.cnblogs.com/wsyphaha/p/15080904.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!