原型模式用于創(chuàng)建重復(fù)對象的同時保持性能悦污,該模式屬于創(chuàng)建型設(shè)計模式铸屉,是創(chuàng)建對象的最佳實(shí)現(xiàn)方式。
-
為什么要使用原型模式切端?
-
提高性能:通過
new
的方式創(chuàng)建對象不能獲取到對象運(yùn)行時的狀態(tài)彻坛,且new
復(fù)制給新對象并沒有直接clone
的性能高。 - 逃避構(gòu)造函數(shù):原型模式生成的新對象可能是派生類踏枣⌒⊙梗拷貝構(gòu)造函數(shù)生成的新對象只能是它本身。
-
提高性能:通過
-
何時使用原型模式椰于?
- 對象之間相同或相似怠益,即只有個別幾個屬性不同的時候
- 對象的創(chuàng)建過程比較麻煩,但復(fù)制比較簡單的時候
- 資源優(yōu)化場景瘾婿,在實(shí)際項(xiàng)目中蜻牢,原型模式很少單獨(dú)出現(xiàn),一般和工廠方法模式一起出現(xiàn)偏陪,通過
clone
的方式創(chuàng)建一個對象抢呆,然后由工廠方法提供給調(diào)用者
具體原型類:實(shí)現(xiàn)抽象原型類的clone()
方法,它是可被復(fù)制的對象
原型模式實(shí)踐
- 優(yōu)點(diǎn)
- 簡化對象的創(chuàng)建笛谦,提高性能抱虐,它可直接操作內(nèi)存中的二進(jìn)制流,特別是復(fù)制大對象饥脑,性能差別非常明顯
- 缺點(diǎn)
- 實(shí)現(xiàn)原型模式的每個派生類都必須實(shí)現(xiàn)
Clone
接口
- 實(shí)現(xiàn)原型模式的每個派生類都必須實(shí)現(xiàn)
代碼實(shí)現(xiàn)
package prototype;
import java.io.Serializable;
public class Person implements Serializable , Cloneable{
private String name;
public Person(String name) {
this.name = name;
}
public Person() {
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
@Override
public Person clone() {
try {
// TODO: copy mutable state here, so the clone can't change the internals of the original
return (Person) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
package prototype;
public class Client {
public static void main(String[] args) {
Person person = new Person("person1");
Person person1 = person.clone();
System.err.println("person == person1?" + (person == person1));
System.err.println(person1);
}
}
// 結(jié)果
person == person1false
Person{name='person1'}