Java SDK中的原型模式Cloneable接口和clone()方法
原型模式是一种创建型设计模式,它使用原型对象来创建新的对象,而无需和具体对象的类相耦合。在Java SDK中,原型模式的实现主要依靠Cloneable接口和clone()方法。
1. Cloneable接口:
Cloneable接口是一个空接口,它只是用来标识一个类可以被复制。实现了Cloneable接口的类可以使用clone()方法来创建对象的副本。
2. clone()方法:
clone()方法是Object类中的一个protected方法,它用于创建并返回调用它的对象的一份副本。要使用clone()方法,需要在自定义的类中重写该方法,并且在方法中调用super.clone()。
下面是一个使用原型模式的框架代码的完整原码示例:
class Prototype implements Cloneable {
private String name;
public Prototype(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Prototype prototype = new Prototype("Prototype");
Prototype clone = (Prototype) prototype.clone();
System.out.println("Original: " + prototype.getName());
System.out.println("Clone: " + clone.getName());
}
}
在上述示例中,创建了一个原型类Prototype,并且实现了Cloneable接口。在Main类的main方法中,先创建了一个原型对象prototype,然后通过调用clone()方法创建了一个克隆对象clone。最后,分别打印原型对象和克隆对象的名称。
总结:
原型模式通过复制已有的对象来创建新的对象,避免了与具体对象类的耦合。在Java中,原型模式的实现依赖于Cloneable接口和clone()方法。需要注意的是,使用原型模式创建对象时,原型对象的构造函数不会被执行,对象的复制是通过调用clone()方法来实现的。