Clone() dùng để clone object tức là nhân bản đối tượng, nó thường rất hiệu quả trong việc chúng ta cần một đối tượng gần giống hoặc giống đối tượng đã có.
Giả sử ta có đối tượng iPhone4 với rất nhiều thuộc tính (camera, màu sắc, thiết kế, pin, hệ điều hành, ....) khó mà liệt kê hết, do có nhiều thuộc tính như vậy thì khi sản xuất phiên bản iPhone5 thì người ta sẽ nghĩ đến các chi tiết chính sẽ thay đổi (thiết kế, hệ điều hành, dung lượng pin) chẳng hạn, như bậy thìiPhone5 chính là phiên bản IPhone 5 mới nhưng IPhone 5 có hai mẫu là IPhone 5C và IPhone 5S vậy điểm khác biệt sẽ thực hiệnPHP:IPhone iPhone5 = iPhone4.clone();iPhone5.setThietKe(new ThietKe12254512());iPhone5.setHeDieuHanh(new HeDieuHanh12355());iPhone5.setDungLuongPin(n));
PHP:IPhone iPhone5C = iPhone5.clone();iPhone5C.setMemory(32);iPhone5C.setCamera(12);
IPhone iPhone5S = iPhone5.clone();iPhone5S.setMemory(12);iPhone5S.setCamera(6);
Prototype. Loại: Creation. Độ khó: Thấp
Prototype theo tiếng Anh là mẫu vật. Dựa trên mẫu vật mà người ta copy ra nhiều đối tượng khác có cùng tính chất và hành vi. Java hỗ trợ 1 interface Cloneable với phương thức clone.
public class Complex implements Cloneable {
int[] nums = {1,2,3,4,5};
public Object clone() {
try {
return super.clone();
}catch(CloneNotSupportedException cnse) {
System.out.println(cnse.getMessage());
return null;
}
}
int[] getNums() {
return nums;
}
}
public static void main(String[] args)
{
Complex complex1 = new Complex();
Complex copy = (Complex)complex1.clone();
complex1.getNums()[3] = 10000;
for(int i = 0; i < copy.getNums().length; i++)
System.out.println(copy.getNums()[i]);
}
public class Complex implements Cloneable {
int[] nums = {1,2,3,4,5};
public Object clone() {
try {
return super.clone();
}catch(CloneNotSupportedException cnse) {
System.out.println(cnse.getMessage());
return null;
}
}
int[] getNums() {
return nums;
}
}
public static void main(String[] args)
{
Complex complex1 = new Complex();
Complex copy = (Complex)complex1.clone();
complex1.getNums()[3] = 10000;
for(int i = 0; i < copy.getNums().length; i++)
System.out.println(copy.getNums()[i]);
}
No comments:
Post a Comment