簡體   English   中英

如何實現原型模式?

[英]How to implement the prototype pattern?

原型模式的目標是通過降低創建成本來克隆對象。 這是一個例子:

class Complex {
    int[] nums = {1,2,3,4,5};
    public Complex clone() {
        return new Complex();//this line create a new object, so is it violate the objective             of prototype ?//
    }
}

class Test2 {
   Complex c1 = new Complex();
   Complex makeCopy() {
      return (Complex)c1.clone();// Is it actually create a new object ? based on the clone method in Complex class? //
   }
   public static void main(String[] args) {
       Test2 tp = new Test2();
       Complex c2 = tp.makeCopy();
   }
}

我認為這是深刻的復制。 所以,有人可以幫我解決這個問題嗎?

首先,為了使這個工作,您的Complex類需要實現Cloneable標記接口,以向Object.clone()方法指示該方法合法地為該類的實例創建一個字段的字段副本。 然后,您需要重寫Object.clone()方法以指定復制行為:

public Complex clone(){
    Complex clone = (Complex)super.clone();
    clone.nums = this.nums;
    return clone;
}

我不認為給出的示例是按照Prototype Pattern實現的。

我看到的錯誤是:

  1. 未實現可克隆標記接口。
  2. 正在使用重寫克隆方法中的“new Complex()”構造函數創建新實例。 情況並非如此。 我的意思是在原型模式中我們應該復制源代碼,進行一些更改並根據需要使用克隆。 但不是創建新實例。 通過克隆實例創建的成本可以避免,但如果我們重寫克隆方法並創建它自己的實例,你實際上增加了它的成本。

一些用於理解Prototype Pattern的鏈接:

http://www.javabeat.net/tips/34-using-the-prototype-pattern-to-clone-objects.html

http://www.allapplabs.com/java_design_patterns/prototype_pattern.htm

用於clone方法的java實現不會調用類構造函數。 它會將當前實例占用的內存復制到內存中的另一個位置。

這種方式真正降低了新對象創建的成本。

你所說的部分是正確的,因為原型模式的目標是通過克隆和避免“新”來降低創建對象的成本。

但這並不意味着您可以使用該模式來克隆對象。 還有其他重要的考慮因素

  • 使用原型對象作為所有其他實例的“制造者”。
  • 從給定實例(原型)創建“幾乎”類似的實例

總而言之,原型的目標是:

  • 通過克隆“原型對象”來降低創建對象的成本
  • 當通過原型設計創建的對象與原型對象略有不同時。

下面是一個使用原型PageBanner實例創建不同類型的頁面橫幅的示例,這些頁面橫幅略有不同

 import java.awt.Dimension;
 import java.io.Serializable;

/**
 * This class also acts as a factory for creating prototypical objects.
 */
public class PageBanner implements Serializable, Cloneable  {
   private String slogan;
   private String image;
   private String font;
   private Dimension dimension;

   // have prototype banner from which to derive all other banners
   private static final PageBanner PROTOTYPE = new PageBanner("", 
       "blank.png", "Verdana", new Dimension(600, 45));

   PageBanner(String slogan, String image, String font, 
         Dimension dim)   {
      this.slogan = slogan;
      this.image = image;
      //... other assignments
   }

   // getters and setters..

   public String toString()   {
      return new StringBuilder("PageBanner[")
            .append("Slogan=").append(slogan)
            .append("Image=").append(image)
            .append("Font=").append(font)
            .append("Dimensions=").append(dimension)
            .toString();

   }

   protected Object clone()  {
      Object cln = null;
      try   {
         cln = super.clone();
      }catch(CloneNotSupportedException e)   {
         // ignore, will never happen
      }
      return cln;
   }

   /**
    * This is the creational method that uses the prototype banner 
    * to create banners and changes it slightly (setting slogan and image)
    */
   public static PageBanner createSloganBanner(String slogan, String image)   {
      PageBanner banner = (PageBanner) PROTOTYPE.clone();
      banner.slogan = slogan;
      banner.image = image;
      return banner;
   }

   /**
    * Another creational method that uses the prototype banner 
    * to create banners and changes it slightly (setting image)
    */
   public static PageBanner createImageBanner(String image)   {
      PageBanner banner = (PageBanner) PROTOTYPE.clone();
      banner.image = image;
      return banner;
   }

   // similarly you can have a number of creational methods with 
   // different parameters for different types of banners that 
   // vary slightly in their properties.

   // main... (for illustration)
   public static void main(String[] args) {
      // both these banners are created from same prototypical instance
      PageBanner slogan = PageBanner.createSloganBanner(
            "Stackoverflow Rocks", "stack.png");
      PageBanner img = PageBanner.createImageBanner("stackBanner.png");
   }
}

哦,在你的情況下,讓你的原型對象的類實現Cloneable標記接口

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM