原型模式

继承Cloneable接口,重写clone()方法。

public class Sheep implements Cloneable {
    private String name;
    private int age;
    private String color;

    public Sheep(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }

    @Override
    protected Object clone() {
        Sheep sheep=null;
        try {
            sheep = (Sheep) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return sheep;
    }
}

import yuanxingmoshi.Sheep;

public class Client {
    public static void main(String[] args) {
        Sheep sheep = new Sheep("小白", 13, "白色");
        System.out.println(sheep);
        System.out.println(sheep.hashCode());
        Sheep sheep1 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        System.out.println(sheep1);
        System.out.println(sheep1.hashCode());
    }
}
  1. 原型模式在Spring框架中源码分析:原型bean的创建,就是原型模式的应用
  2. 浅拷贝和深拷贝:对于浅拷贝就是使用默认的clone()方法来实现,它的特点为浅拷贝会对基本数据类型直接进行值传递,对引用类型进行引用传递。通俗来说,基本数据类型值传递而已,hashcode会变化。引用类型只是加了一个指针,没有加额外的空间。
  3. 深拷贝为整个对象进行拷贝,复制了对象的所有基本类型的成员变量值,为所有引用类型的成员变量申请了存储空间。
  4. 深拷贝实现方式有两种:一种重写clone方法来实现 一种通过对象序列化实现
@Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        /*完成对基本类型的克隆*/
        deep=super.clone();
        /*对引用类型的属性单独处理*/
        /*强转*/
        SheepType sheep = (SheepType) deep;
        /*对强转后的对象的属性进行clone*/
        sheep.sheep = (Sheep) sheep.clone();

        return sheep;
    }

个人觉的就是两层浅拷贝,先利用基础的拷贝,在单独进行一个拷贝。

ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStrean bis= null;
ObjectInputStream ois = null;
//序列化
bos = new ByteArrayOutputStream bos ;
oos = new ObjectOutputStream (bos);
oos.writeObject(this);//当前对象以对象流的方式输出
//反序列化
//释放资源