Java設計模式之(四)——原型模式

1、什麼是原型模式

Specify the kinds of objects to create using a prototypical instance,and create new objects by copying this prototype.

Prototype Design Pattern:用原型實例指定創建對象的種類, 並且通過拷貝這些原型創建新的對象。

說人話:對象複製

2、原型模式的兩種實現方法

我們日常開發中,應該有使用過 BeanUtils.copyProperties()方法,其實這就是原型模式的一種用法(淺拷貝)。原型模式實現分兩種:

①、淺拷貝:只會複製對象中基本數據類型數據和引用對象的內存地址,不會遞歸地複製引用對象,以及引用對象的引用對象

②、深拷貝:得到的是一份完完全全獨立的對象。

Java 中 Object 類是所有類的根類,Object 類提供了一個 clone()方法,該方法可以將一個 Java 對象複製一份,但是在調用 clone方法的Java類必須要實現一個接口Cloneable,這是一個標誌接口,標誌該類能夠複製且具有複製的能力,如果不實現 Cloneable 接口,直接調用clone方法,會拋出 CloneNotSupportedException 異常。

/**
 * A class implements the <code>Cloneable</code> interface to
 * indicate to the {@link java.lang.Object#clone()} method that it
 * is legal for that method to make a
 * field-for-field copy of instances of that class.
 * <p>
 * Invoking Object's clone method on an instance that does not implement the
 * <code>Cloneable</code> interface results in the exception
 * <code>CloneNotSupportedException</code> being thrown.
 * <p>
 * By convention, classes that implement this interface should override
 * <tt>Object.clone</tt> (which is protected) with a public method.
 * See {@link java.lang.Object#clone()} for details on overriding this
 * method.
 * <p>
 * Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
 * Therefore, it is not possible to clone an object merely by virtue of the
 * fact that it implements this interface.  Even if the clone method is invoked
 * reflectively, there is no guarantee that it will succeed.
 *
 * @author  unascribed
 * @see     java.lang.CloneNotSupportedException
 * @see     java.lang.Object#clone()
 * @since   JDK1.0
 */
public interface Cloneable {
}

關於深淺拷貝的詳細說明,可以參考我的這篇博客:

//www.cnblogs.com/ysocean/p/8482979.html

3、原型模式的優點

①、性能高

原型模式是在內存二進制流的拷貝, 要比直接new一個對象性能好很多, 特別是要在一個循環體內產生大量的對象時, 原型模式可以更好地體現其優點。

②、避免構造函數的約束

這既是它的優點也是缺點,直接在內存中拷貝,構造函數是不會執行的 。 優點就是減少了約束, 缺點也是減少了約束, 需要大家在實際應用時考慮。

4、原型模式使用場景

①、在需要一個類的大量對象的時候,使用原型模式是最佳選擇,因為原型模式是在內存中對這個對象進行拷貝,要比直接new這個對象性能要好很多,在這種情況下,需要的對象越多,原型模式體現出的優點越明顯。

②、如果一個對象的初始化需要很多其他對象的數據準備或其他資源的繁瑣計算,那麼可以使用原型模式。

③、當需要一個對象的大量公共信息,少量字段進行個性化設置的時候,也可以使用原型模式拷貝出現有對象的副本進行加工處理。