概念
用原型實例指定創(chuàng)建對象的種類悴务,并通過拷貝這些原型創(chuàng)建新的對象浇冰。
優(yōu)缺點
- 使用原型模式創(chuàng)建對象比直接new一個對象在性能上要好的多水援,因為Object類的clone方法是一個本地方法矗蕊,它直接操作內(nèi)存中的二進(jìn)制流疙驾,特別是復(fù)制大對象時阀趴,性能的差別非常明顯
- 簡化對象的創(chuàng)建昏翰,使得創(chuàng)建對象就像我們在編輯文檔時的復(fù)制粘貼一樣簡單
- 在需要重復(fù)地創(chuàng)建相似對象時可以考慮使用原型模式。比如需要在一個循環(huán)體內(nèi)創(chuàng)建對象舍咖,假如對象創(chuàng)建過程比較復(fù)雜或者循環(huán)次數(shù)很多的話矩父,使用原型模式不但可以簡化創(chuàng)建過程,而且可以使系統(tǒng)的整體性能提高很多
結(jié)構(gòu)與參與者
代碼示例
// 原型類要實現(xiàn)Cloneable接口排霉,在運行時通知虛擬機可以安全地在實現(xiàn)了此接口的類上使用clone方法窍株,因為只有實現(xiàn)了這個接口的類才可以被拷貝
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("原型模式實現(xiàn)類");
}
}
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開發(fā)中無處不在的設(shè)計模式——原型模式
23種設(shè)計模式(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?
設(shè)計模式包教不包會
六個創(chuàng)建模式之原型模式(Prototype Pattern)