본문 바로가기
디자인패턴

Prototype 패턴

by 갈잃자 2025. 9. 12.

prototype  패턴이란?

  • 복제 기반으로 객체를 생성하는 패턴
  • new 를 직접 쓰지 않고, 이미 존재하는 객체를 복사해서 새로운 객체를 만드는 방식
  • 원형(prototype)객체를 두고, 그걸 복사해서 새로운 인스턴스를 만든다는 개념

언제 쓰나?

  • 객체 생성 비용이 클 때
  • 비슷한 객체를 여러 개 만들어야 하는데, 값만 조금씩 바뀌는 경우
  • 객체 구조가 복잡해서 생성자 호출보다 복제하는 게 더 효율적일 때

구조설명

 

그냥 new로 사용하는 경우

class Document {
  constructor(
    public title: string,
    public content: string,
    public author: string
  ) {}
}

const doc1 = new Document("계약서", "내용...", "홍길동");
const doc2 = new Document("계약서", "내용...", "홍길동"); // 또 생성해야 함

 

prototype 패턴 적용

interface Prototype<T> {
  clone(): T;
}

class Document implements Prototype<Document> {
  constructor(
    public title: string,
    public content: string,
    public author: string
  ) {}

  clone(): Document {
    // 얕은 복사
    return new Document(this.title, this.content, this.author);
  }
}

const doc1 = new Document("계약서", "내용...", "홍길동");
const doc2 = doc1.clone();
doc2.author = "김철수";

console.log(doc1); // author: 홍길동
console.log(doc2); // author: 김철수

 

얕은복사, 깊은복사 확인하기

 

현재 상황은 얕은복사라, doc2의 값을 변경했을때, doc1도 변경될 우려가 보임.

 

하지만, 복사되는 필드들이 기본타입 이라서 참조 공유 문제가 없다..!

따라서, doc2.author를 변경해도 doc1에는 영향이 없음.

 

만약 Document 내부에 객체로 된 데이터가 있다면?

class Document {
  constructor(
    public title: string,
    public content: string,
    public meta: { author: string }
  ) {}

  clone(): Document {
    return new Document(this.title, this.content, this.meta); // 얕은 복사
  }
}

const doc1 = new Document("계약서", "내용...", { author: "홍길동" });
const doc2 = doc1.clone();

doc2.meta.author = "김철수";

console.log(doc1.meta.author); // 김철수 (참조 공유됨)
console.log(doc2.meta.author); // 김철수

 

얕은복사는 depth 1 까지만 복사가 되고, 객체 내부 참조값은 공유가 되므로, 위 상황부턴 얕은복사를 사용할 수 없음

 

위같은 이유로 prototype패턴은 잘 보이지 않고, 특히 현대 언어들에 복제 도구가 많이 나왔기 때문에, 더더욱 잘 쓰이지 않는 패턴이다.

'디자인패턴' 카테고리의 다른 글

Builder 패턴  (0) 2025.09.09
Abstract Factory (추상 팩토리 패턴)  (0) 2025.09.09
Factory Method 패턴  (0) 2025.09.09
singleton(싱글턴) 패턴  (0) 2025.09.05

댓글