2010-08-20 4 views
5

프로토 타입 패턴의 목적은 생성 비용을 줄임으로써 객체를 복제하는 것입니다. 다음은 예입니다.프로토 타입 패턴을 구현하는 방법은 무엇입니까?

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(); 
    } 
} 

딥 복사본이라고 생각합니다. 그래서, 누군가이 질문에 나를 도울 수 있습니까 ???

+0

위 패턴의 Wikipedia의 정의도 확인했습니다. 객체 캐시를 사용하지 않는다면 클래스가 인스턴스화되고 있다는 의미가 없다는 것에 동의합니다. –

답변

1

우선이 작업을 수행하기 위해 Complex 클래스는 Cloneable 마커 인터페이스를 구현하여 Object.clone() 메서드에 인스턴스의 필드 필드 복사본을 만드는 것이 합법임을 나타낼 수 있어야합니다. 그 계급의 그런 다음 Object.clone() 메서드를 재정 의하여 복사 동작을 지정해야합니다.

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

나는 OP가 프로토 타입 패턴 뒤에있는 이론에 대해 묻고 있다고 생각 했지? 그리고 실제로 새로운 객체를 인스턴스화하는지 여부는 ... –

0

주어진 예제가 프로토 타입 패턴에 따라 구현되지 않았다고 생각합니다. 내가 볼

실수는 다음과 같습니다

  1. Cloneable을 마커 인터페이스를 구현 가 없습니다.
  2. 재정의 된 복제 방법에서 "new Complex()"생성자를 사용하여 새 인스턴스를 만듭니다. 이 이 아니어야합니다. 무슨 뜻 이죠 여기서 우리는 소스의 사본을 만들어 약간의 변경을하고 요구 사항에 따라 클론을 사용해야합니다 프로토 타입 패턴입니다. 하지만 새로운 인스턴스를 만들지는 않습니다. 인스턴스 생성 비용을 복제함으로써 피할 수 있지만, 복제 방법을 재정의하고 인스턴스를 생성하면 실제로 비용이 증가합니다. 프로토 타입 패턴을 이해하기위한

일부 링크 : 복제 방법

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

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

0

자바 구현 클래스의 생성자를 호출하지 않습니다. 현재 인스턴스가 차지하는 메모리를 메모리의 다른 위치로 복사합니다.

이렇게하면 새 개체 생성 비용이 크게 절감됩니다.

0

프로토 타입 패턴의 목적은 "새로운"복제 및 피하기로 객체 생성에 드는 비용을 줄이는 것입니다.

그러나 그렇다고해서 개체 복제에만 패턴을 사용할 수있는 것은 아닙니다. 다른 중요한 고려 사항이 있습니다

  • 프로토 타입 개체를 다른 모든 인스턴스의 "제조 업체"로 사용하십시오.

    • 는 "프로토 타입 객체를 복제하여 생성 객체의 비용 절감 :
    • 는"거의 "유사한 인스턴스가 지정된 인스턴스,

    가 요약하면 프로토 타입을 형성 만들기, 프로토 타입의 목적은하는 것입니다 "

  • 프로토 타이핑으로 생성 된 객체가 프로토 타입 객체와 약간 다를 수 있습니다.다음은

은 프로토 타입 객체의 클래스가 Cloneable 마커 인터페이스를 구현 한 약간

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"); 
    } 
} 

아, 그리고 귀하의 경우 차이가 서로 다른 유형의 페이지 배너 을 만들기 위해 원형 PageBanner 인스턴스를 사용하는 예입니다