5. 프로토타입 패턴(Prototype)

김해준's avatar
Dec 03, 2025
5. 프로토타입 패턴(Prototype)

Prototype 패턴이란?

⭐ 한 줄 정의

새 객체를 new로 만드는 대신, 기존 객체를 복사(clone)해서 새로운 객체를 만드는 생성 패턴.
즉,
객체의 생성 비용이 크거나
비슷한 객체를 여러 개 만들어야 할 때
Prototype 패턴을 사용하면 훨씬 효율적이다.

📌 Prototype 패턴을 쓰는 이유

✔ (1) 객체를 복잡하게 초기화할 필요 없음

기존 객체를 그대로 복사하면 되므로 초기화 비용 절감.

✔ (2) 비슷한 구성의 객체 다수를 쉽게 생성

템플릿 객체만 하나 만들고 .clone()으로 복제.

✔ (3) 상태가 유사한 객체를 빠르게 만들 수 있음

특히 게임 개발에서 "기본 스탯을 가진 몬스터/아이템 복사"에 유용.

📌 Prototype 패턴 구조

Prototype (인터페이스/추상 클래스) └─ clone() 메서드를 선언 Concrete Prototype (구현 클래스) └─ clone()을 통해 자기 자신을 복제
자바에서는 보통 다음 중 하나로 구현한다.
  1. Cloneable + clone() 오버라이드
  1. 복사 생성자 + 사용자 정의 Clone() 메서드

🧪 예시 코드

아래 코드는 복사 생성자 + Clone() 메서드 방식의
가장 깔끔한 Prototype 패턴 구현이다.
package ex04; public class People implements Cloneable { private String name; private int height; private int weight; // (1) 기본 생성자 People() {} // (2) 일반 생성자 People(String name, int height, int weight) { this.name = name; this.height = height; this.weight = weight; } // (3) 복사 생성자 (Prototype 핵심) People(People origin) { this.name = origin.name; this.height = origin.height; this.weight = origin.weight; } // (4) Prototype 패턴: 복제 메서드 public People Clone() { return new People(this); // 복사 생성자 이용 } // 상태 변화 메서드 public void eat() { weight += 2; } public int getWeight() { return weight; } // ---------- Builder 패턴 ---------- static class Builder { String name; int height; int weight; public Builder setName(String name) { this.name = name; return this; } public Builder setHeight(int height) { this.height = height; return this; } public Builder setWeight(int weight) { this.weight = weight; return this; } public People build() { return new People(this); } } // 빌더 생성자 People(Builder builder) { this.name = builder.name; this.height = builder.height; this.weight = builder.weight; } }

🏃‍♂️ 사용 코드 (Prototype 활용 예)

package ex04; public class PeopleApp { public static void main(String[] args) { // Builder로 People 객체 생성 People people1 = new People.Builder() .setName("홍길동") .setHeight(170) .setWeight(50) .build(); people1.eat(); people1.eat(); System.out.println("people1 체중 = " + people1.getWeight()); // Prototype 패턴: 기존 객체 복사 People people2 = people1.Clone(); System.out.println("people2 체중 = " + people2.getWeight()); } }

🎉 Prototype 패턴 핵심 요약

✔ Prototype = 복제 기반 객체 생성

클래스를 new로 직접 만들지 않고
기존 객체를 복사해서 새로운 객체를 생성하는 방식이다.

✔ 복사 생성자 혹은 clone()을 사용

  • 단순 복제 → 얕은 복사
  • 깊은 복제 → 복사 생성자 사용

✔ 언제 쓰나?

  • 초기화 비용이 큰 복잡한 객체
  • 상태가 비슷한 객체를 많이 만들어야 할 때
  • 템플릿 기반 객체 생성 시

✔ 장점

  • 성능 향상
  • 코드 단순화
  • 객체 생성 구조 재사용 쉬움

✔ 단점

  • 깊은 복사/얕은 복사 관리가 어려울 수 있음

✓정리하면

“기존 객체를 복사해서 새로운 객체를 만드는 패턴” = Prototype 패턴
Share article