概念
用原型實例指定創(chuàng)建對象的種類,并通過拷貝這些原型創(chuàng)建新的對象。
優(yōu)缺點
- 使用原型模式創(chuàng)建對象比直接new一個對象在性能上要好的多,因為Object類的clone方法是一個本地方法,它直接操作內存中的二進制流,特別是復制大對象時,性能的差別非常明顯
- 簡化對象的創(chuàng)建,使得創(chuàng)建對象就像我們在編輯文檔時的復制粘貼一樣簡單
- 在需要重復地創(chuàng)建相似對象時可以考慮使用原型模式。比如需要在一個循環(huán)體內創(chuàng)建對象,假如對象創(chuàng)建過程比較復雜或者循環(huán)次數(shù)很多的話,使用原型模式不但可以簡化創(chuàng)建過程,而且可以使系統(tǒng)的整體性能提高很多
結構與參與者
代碼示例
// 原型類要實現(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ā)中無處不在的設計模式——原型模式
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?
設計模式包教不包會
六個創(chuàng)建模式之原型模式(Prototype Pattern)