zoukankan      html  css  js  c++  java
  • Prototype原型模式

    原型模式就是以一个对象作为原型构建另一个对象,也就是我们说的克隆。

    克隆做法是什么呢?

      对象实现克隆接口Clonable接口,将访问方法clone重写,访问权限变大。

    默认的克隆是浅拷贝,指的是外层对象是new的,但是对象的属性都是通过值copy给的的,也就会出现一个问题,引用数据类型用的都是同一个对象

    深拷贝的做法:

       重写clone方法,针对每一个引用数据类型new 一个对象,只是将基本数据类型的值放入进去该对象

      或者可以利用序列化做媒介完成,深拷贝。

    代码:

    package com.zhen.build_template.prototype;
    
    import java.io.*;
    
    /**
     * @author zhen
     * @Date 2019/5/28 21:48
     */
    public class Prototype implements Cloneable, Serializable{
        public String name = "嘻嘻";
        public C c = new C("张三", 2);
        @Override
        public Object clone() throws CloneNotSupportedException {
            Prototype prototype =  (Prototype) super.clone();
            return prototype;
        }
    
        public Object deepClone() throws IOException, ClassNotFoundException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
    
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            Object obj = ois.readObject();
            return obj;
    
        }
    
        public Object deepClone1()  throws CloneNotSupportedException{
            Prototype object = (Prototype) super.clone();
            object.c = new C(this.c.name, this.c.age);
            return object;
        }
    
    }
    
    class C implements Serializable{
        public String name;
        public int age;
        public C(String name, int age){
            this.age = age;
            this.name = name;
        }
    }
    
    
    package com.zhen.build_template.prototype;
    
    /**
     * @author zhen
     * @Date 2019/5/28 21:50
     */
    public class TestClone {
        public static void main(String[] args) throws Exception{
            Prototype prototype = new Prototype();
            Prototype prototype1 = (Prototype) prototype.clone();
            System.out.println(prototype.equals(prototype1));
            System.out.println(prototype.name.equals(prototype1.name));
            System.out.println(prototype.c.equals(prototype1.c));
    
            Prototype prototype2 = (Prototype) prototype.deepClone();
            System.out.println(prototype.equals(prototype2));
            System.out.println(prototype.name==prototype2.name);
            System.out.println(prototype.c.equals(prototype2.c));
            System.out.println(prototype.c.name==prototype2.c.name);
        }
    }
    View Code
  • 相关阅读:
    快速幂 快速乘法
    扩展欧几里得学习笔记
    求逆序数数目(树状数组+离散化)
    隐式图的遍历
    随机数生成
    推倒重来
    动态规划初步
    子集生成
    东大oj1155 等凹函数
    P1278 单词游戏
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/10942760.html
Copyright © 2011-2022 走看看