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

7번째 줄: 7번째 줄:
* 일반적으로 객체를 생성할 때는 new를 사용하는데, 초기값이 아니라 어떤 객체의 상태를 복제하여 사용하고 싶은 경우에 적용한다.
* 일반적으로 객체를 생성할 때는 new를 사용하는데, 초기값이 아니라 어떤 객체의 상태를 복제하여 사용하고 싶은 경우에 적용한다.
* private 필드도 복제할 수 있어야 한다.
* private 필드도 복제할 수 있어야 한다.
* 깊은 복사/얕은 복사 어느 것을 것인가?
* 들고 있는 객체가 있다면, 깊은 복사/얕은 복사 어느 것을 적용할 것인가?
* Java에는 Cloneable이라는 인터페이스가 있긴 하다.
* Java에는 Cloneable이라는 인터페이스가 있긴 하다.



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

1 개요

prototype pattern
프로토타입 패턴
  • 인스턴스를 복제하여 사용하는 구조
  • 생성할 객체들의 타입이 프로토타입 인스턴스로부터 결정되도록 하는 디자인 패턴
  • 인스턴스는 새 객체를 만들기 위해 자신을 복제(clone)한다.
  • 일반적으로 객체를 생성할 때는 new를 사용하는데, 초기값이 아니라 어떤 객체의 상태를 복제하여 사용하고 싶은 경우에 적용한다.
  • private 필드도 복제할 수 있어야 한다.
  • 들고 있는 객체가 있다면, 깊은 복사/얕은 복사 중 어느 것을 적용할 것인가?
  • Java에는 Cloneable이라는 인터페이스가 있긴 하다.

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 }}