概念
用原型實例指定創建對象的種類,并通過拷貝這些原型創建新的對象。
優缺點
- 使用原型模式創建對象比直接new一個對象在性能上要好的多,因為Object類的clone方法是一個本地方法,它直接操作內存中的二進制流,特別是復制大對象時,性能的差別非常明顯
- 簡化對象的創建,使得創建對象就像我們在編輯文檔時的復制粘貼一樣簡單
- 在需要重復地創建相似對象時可以考慮使用原型模式。比如需要在一個循環體內創建對象,假如對象創建過程比較復雜或者循環次數很多的話,使用原型模式不但可以簡化創建過程,而且可以使系統的整體性能提高很多
結構與參與者
代碼示例
// 原型類要實現Cloneable接口,在運行時通知虛擬機可以安全地在實現了此接口的類上使用clone方法,因為只有實現了這個接口的類才可以被拷貝
class Prototype implements Cloneable {
public Prototype clone(){
Prototype prototype = null;
try{
prototype = (Prototype)super.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return prototype;
}
}
class ConcretePrototype extends Prototype{
public void show(){
System.out.println("原型模式實現類");
}
}
public class Client {
public static void main(String[] args){
ConcretePrototype cp = new ConcretePrototype();
for(int i=0; i< 10; i++){
ConcretePrototype clonecp = (ConcretePrototype)cp.clone();
clonecp.show();
}
}
}
參考資料
Youtube
Android開發中無處不在的設計模式——原型模式
23種設計模式(5):原型模式
Prototype Pattern
Prototype Pattern Tutorial with Java Examples
Design pattern: singleton, prototype and builder
原型模式(Proxy Pattern)
What's the point of the Prototype design pattern?
設計模式包教不包會
六個創建模式之原型模式(Prototype Pattern)