多例模式

1 概念

原型模式=多例模式

原型模式是通过调用原对象的 Clone方法,来创建另一个新的对象,而无须知道创建的细节。

在Java中,只需要原型类实现Cloneable接口并实现 Clone方法即可。

2 浅复制

对象的基本类型的变量值会被重新创建和复制

但引用类型仍指向原来的原来对象的引用。

public class Computer implements Cloneable {
    
    private String cpu;
    private String memory;
    private String disk;

    public Computer(String cpu, String memory, String disk) {
        this.cpu = cpu;
        this.memory = memory;
        this.disk = disk;
    }

    @Override
    protected Computer clone(){
        try {
            return (Computer)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }
}

3 深拷贝

public class DeepCloneComputer implements Cloneable {

    private String cpu;
    private String memory;
    public Disk disk;

    public DeepCloneComputer(String cpu, String memory, Disk disk) {
        this.cpu = cpu;
        this.memory = memory;
        this.disk = disk;
    }

    @Override
    protected DeepCloneComputer clone() throws CloneNotSupportedException {
        DeepCloneComputer deepCloneComputer = (DeepCloneComputer)super.clone();
        deepCloneComputer.disk = (Disk)disk.clone();
        return  deepCloneComputer;
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Disk disk = new Disk("128","500");
        DeepCloneComputer deepCloneComputer = new DeepCloneComputer("12core", "8G", disk);
        System.out.println(deepCloneComputer);
        DeepCloneComputer clone = (DeepCloneComputer)deepCloneComputer.clone();
        System.out.println(clone);
        System.out.println(deepCloneComputer==clone);
    }
}
class Disk implements Cloneable{
    private String ssd;
    private String hhd;

    public Disk(String ssd, String hhd) {
        this.ssd = ssd;
        this.hhd = hhd;
    }

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

class Computer{
    private String cpu;
    private String memory;
    public Disk disk;

    public Computer(String cpu, String memory, Disk disk) {
        this.cpu = cpu;
        this.memory = memory;
        this.disk = disk;
    }
}

Spring中bean的作用范围其中一个是prototype原型模式,

这个其实就是深拷贝,所以拷贝出来的对象和原来不是同一个。

4 总结

怎么实现深拷贝呢?

1-这个类和类中引用成员变量都要继承 Cloneable接口并实现方法。

2-赋值的时候要采用car.wheel = (Wheel)wheel.clone()来赋值。

posted @ 2021-12-11 22:49  姚狗蛋  阅读(28)  评论(0编辑  收藏  举报