其實這個設計模式就是我們通常說的對象拷貝,直接看代碼吧
/**
* 原型設計模式
* 把一個有狀態的對象複製出多個這種狀態的對象
*/
public class Main {
public static void main(String[] args) {
Prototype prototype1 = new Prototype();
prototype1.setAnimal("cat");
prototype1.setColor("white");
//先生成第一個對象
System.out.println(prototype1);
Prototype prototype2 = (Prototype) prototype1.clone();
//複製出第二個對象
System.out.println(prototype2);
//這兩個對象的屬性都一樣,但是實例是不一樣的
System.out.println(prototype1 == prototype2);
}
}
public class Prototype implements Serializable {
private String animal;
private String color;
public String getAnimal() {
return animal;
}
public void setAnimal(String animal) {
this.animal = animal;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Object clone(){
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(output);
out.writeObject(this);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
ObjectInputStream in = new ObjectInputStream(input);
return in.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public String toString() {
return "Prototype{" +
"animal='" + animal + '\'' +
", color='" + color + '\'' +
'}';
}
}
用法
上面代碼已經看的很清楚了,想複製一個已有的對象,複製出來的對象和原對象的屬性必須完全相同,但是又得是兩個不同的對象,還是說說jquery,裏面的元素也有這種clone方法,做一些元素拖拽的功能時會經常用到,比如把一個節點拖拽到一個區域內,但是原節點還在,我們的很多圖形IDE不也是這樣嗎,從設計器中從文本框圖標中拖拽出一個文本框到編輯區域,這也是很典型的原型模式,都是從已加載元素中進行復制,好了,這篇文章就到這裏了。