设计模式-原型模式

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
实质上是利用实现Cloneable接口的 clone方法来实现对象的克隆。

public class Prototype implements Cloneable{
     
    public Prototype(){
     }

    public Object clone() throws CloneNotSupportedException {
     
        System.out.println("具体原型复制成功!");
        return (Prototype) super.clone();
    }
}

测试类:

public class Test {
     
    public static void main(String[] args) throws CloneNotSupportedException {
     
        Prototype prototype = new Prototype();
        Prototype prototype2 = (Prototype) prototype.clone();
        System.out.println("prototype==prototype2"+(prototype==prototype2));
    }
}

输出:

具体原型复制成功!
prototype==prototype2false

你可能感兴趣的:(java设计模式)