"프로토타입 패턴"의 두 판 사이의 차이

잔글 (봇: 자동으로 텍스트 교체 (-</source> +</syntaxhighlight>, -<source +<syntaxhighlight ))
2번째 줄: 2번째 줄:
;prototype pattern
;prototype pattern
;프로토타입 패턴
;프로토타입 패턴
*인스턴스를 복제하여 사용하는 구조
* 인스턴스를 복제하여 사용하는 구조
*생성할 객체들의 타입이 프로토타입 인스턴스로부터 결정되도록 하는 디자인 패턴
* 생성할 객체들의 타입이 프로토타입 인스턴스로부터 결정되도록 하는 디자인 패턴
*인스턴스는 새 객체를 만들기 위해 자신을 복제(clone)한다.
* 인스턴스는 새 객체를 만들기 위해 자신을 복제(clone)한다.
* 일반적으로 객체를 생성할 때는 new를 사용하는데, 초기값이 아니라 어떤 객체의 상태를 복제하여 사용하고 싶은 경우에 적용한다.


[[파일:Prototype Pattern ZP.svg|500px]]
[[파일:Prototype Pattern ZP.svg|500px]]

2022년 6월 17일 (금) 14:54 판

1 개요

prototype pattern
프로토타입 패턴
  • 인스턴스를 복제하여 사용하는 구조
  • 생성할 객체들의 타입이 프로토타입 인스턴스로부터 결정되도록 하는 디자인 패턴
  • 인스턴스는 새 객체를 만들기 위해 자신을 복제(clone)한다.
  • 일반적으로 객체를 생성할 때는 new를 사용하는데, 초기값이 아니라 어떤 객체의 상태를 복제하여 사용하고 싶은 경우에 적용한다.

Prototype Pattern ZP.svg

2 예제

/**
 * Prototype class
 */
interface Prototype {
    void setX(int x);
 
    void printX();
 
    int getX();
}
 
/**
 * Implementation of prototype class
 */
class PrototypeImpl implements Prototype, Cloneable {
    private int x;
 
    /**
     * Constructor
     */
    public PrototypeImpl(int x) {
        setX(x);
    }
 
    @Override
    public void setX(int x) {
        this.x = x;
    }
 
    @Override
    public void printX() {
        System.out.println("Value: " + x);
    }
 
    @Override
    public int getX() {
        return x;
    }
 
    @Override
    public PrototypeImpl clone() throws CloneNotSupportedException {
        return (PrototypeImpl) super.clone();
    }
}
 
/**
 * Client code
 */
public class PrototypeTest {
    public static void main(String args[]) throws CloneNotSupportedException {
        PrototypeImpl prototype = new PrototypeImpl(1000);
 
        for (int y = 1; y < 10; y++) {
            // Create a defensive copy of the object to allow safe mutation
            Prototype tempotype = prototype.clone();
 
            // Derive a new value from the prototype's "x" value
            tempotype.setX(tempotype.getX() * y);
            tempotype.printX();
        }
    }
}
실행결과
Value: 1000
Value: 2000
Value: 3000
Value: 4000
Value: 5000
Value: 6000
Value: 7000
Value: 8000
Value: 9000

3 같이 보기

4 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}