Prototype 原型模式

2021-10-03 22:29:39 字數 722 閱讀 4941

實現原型模式需要實現標記性介面cloneable 。

一般會重寫clone()方法,如果只重寫clone()方法而沒有實現介面,呼叫是會拋異常。

一般用於乙個物件的屬性已經確定,需要產生許多相同物件的時候。

注意區分淺轉殖和深轉殖。

/**

* 淺轉殖

*/public class test

}class person implements cloneable

}class location ';

}public location(string street, int roomno)

}

/**

* 深轉殖

*/public class test

}class person implements cloneable

}class location implements cloneable ';

}public location(string street, int roomno)

@override

public object clone() throws clonenotsupportedexception

}

原型模式(ProtoType)

1.目的 當需要從乙個物件copy出另外乙個物件時,可以使用原型模式,本質上是呼叫的copy建構函式 與copy建構函式的區別,可能就是不需要顯示的生成物件,而是通過函式呼叫 2.prototype.h ifndef prototype h define prototype h include in...

Prototype 原型模式

prototype 原型模式 所謂原型模式,就是可以根據乙個原型,快速建立出其拷貝。如 int a 1 int b new int a a cout a endl cout b endl 輸出結果 2 1 上面就使用了原型模式。根據原型a,快速建立出了a的拷貝b。同時,b儲存了a當時的狀態。當a之後...

原型模式 Prototype

用原型例項指定建立物件的種類,並且通過拷貝這些原型建立新的物件。原型模式是一種建立型設計模式,它允許乙個物件再建立另外乙個可定製的物件,根本無需知道任何如何建立的細節,工作原理是通過將乙個原型物件傳給那個要發動建立的物件,這個要發動的物件通過請求原型物件拷貝它們自己來實施建立。現實很殘酷,都第9章了...