原型设计模式,被克隆的是什么?

时间:2016-03-12 09:12:55

标签: java design-patterns

我一直在看这个网站的原型模式: http://www.newthinktank.com/2012/09/prototype-design-pattern-tutorial/

在sheep.java第20行中有这段代码:

    sheepObject = (Sheep) super.clone();

当你调用super.close()时,你是不是在复制界面?究竟是什么被克隆了?我不明白羊的田地和方法是如何被克隆的。

// By making this class cloneable you are telling Java
// that it is ok to copy instances of this class
// These instance copies have different results when
// System.identityHashCode(System.identityHashCode(bike))
// is called 

public interface Animal extends Cloneable {

    public Animal makeCopy();

}

public class Sheep implements Animal {

    public Sheep(){

        System.out.println("Sheep is Made");

    }

    public Animal makeCopy() {

        System.out.println("Sheep is Being Made");

        Sheep sheepObject = null;

        try {

            // Calls the Animal super classes clone()
            // Then casts the results to Sheep

            sheepObject = (Sheep) super.clone();

        }

        // If Animal didn't extend Cloneable this error 
        // is thrown

        catch (CloneNotSupportedException e) {

            System.out.println("The Sheep was Turned to Mush");

            e.printStackTrace();

         }

        return sheepObject;
    }

    public String toString(){

        return "Dolly is my Hero, Baaaaa";

    }

}

public class CloneFactory {

    // Receives any Animal, or Animal subclass and
    // makes a copy of it and stores it in its own
    // location in memory

    // CloneFactory has no idea what these objects are
    // except that they are subclasses of Animal

    public Animal getClone(Animal animalSample) {

        // Because of Polymorphism the Sheeps makeCopy()
        // is called here instead of Animals

        return animalSample.makeCopy();

    }

}

public class TestCloning {

    public static void main(String[] args){

        // Handles routing makeCopy method calls to the 
        // right subclasses of Animal

        CloneFactory animalMaker = new CloneFactory();

        // Creates a new Sheep instance

        Sheep sally = new Sheep();

        // Creates a clone of Sally and stores it in its own
        // memory location

        Sheep clonedSheep = (Sheep) animalMaker.getClone(sally);

        // These are exact copies of each other

        System.out.println(sally);

        System.out.println(clonedSheep);

        System.out.println("Sally HashCode: " + System.identityHashCode(System.identityHashCode(sally)));

        System.out.println("Clone HashCode: " + System.identityHashCode(System.identityHashCode(clonedSheep)));
    }

}

2 个答案:

答案 0 :(得分:0)

它调用超类克隆方法。在这种情况下,它看起来像是Object类的clone方法。

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone()

答案 1 :(得分:0)

您需要记住的是,无法实例化接口,任何实例化对象都将是实现所述接口的类。

Animal animalSample 参数将是Animal接口类型,但它指向的对象将是一个实现Animal接口的类,在本例中为 Sheep

因此,当您调用Animal.clone()时,您正在调用正在实现接口的对象的clone方法(Sheep)。