1.定義:用原型實例指定創建對象的種類,並且通過拷貝這些原型創建新的對象。Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
2. 代碼示例
public class Protype implements Cloneable{ //在java裏面原型模式通過實現Cloneable接口便可以降此類進行復制(直接複製內存中的二進制流)
private ArrayList<String> arrayList=new ArrayList<>();
public Protype() //在new 此類的時候構造器會被調用, 而clone不會調用構造器,即不會重新實例化。
{
System.out.println("構造函數調用");
}
@Override
public Protype clone()
{
Protype t=null;
try {
t= (Protype) super.clone(); //此方法複製本類的時候 java中是不會複製原有類的數組和引用的,所有的副本都指向同一個引用,稱爲淺複製
t.arrayList=(ArrayList<String>) this.arrayList.clone(); //深複製 不僅複製本對象,裏面的數組和引用也進行復制。
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
}
************原形模式************
構造函數調用
原型模式適用於直接從內存中複製對象,減少了通過new 的實例化過程。