在Java中,可以通過實(shí)現(xiàn)Cloneable接口和重寫clone()方法來實(shí)現(xiàn)原型設(shè)計(jì)模式。
public class MyClass implements Cloneable {
// 類的成員變量和方法
}
public class MyClass implements Cloneable {
// 類的成員變量和方法
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
MyClass obj1 = new MyClass();
MyClass obj2 = (MyClass) obj1.clone();
需要注意的是,clone()方法是淺拷貝,只會復(fù)制對象的引用,而不會復(fù)制對象的內(nèi)容。如果需要實(shí)現(xiàn)深拷貝,需要在clone()方法中手動復(fù)制對象的內(nèi)容。