프로토타입 패턴 (Prototype)
프로토타입 패턴(Prototype Pattern)은 원본 객체를 복제(Clone)하여 새로운 객체를 생성하는 패턴입니다.
객체를 new 키워드로 생성하고 DB 조회 등을 통해 복잡하게 초기화하는 과정이 매우 비쌀(Cost가 높을) 때, 이미 완벽하게 세팅된 '프로토타입 객체'를 하나 만들어두고 이를 메모리 상에서 통째로 복사해서 사용하면 성능을 극적으로 높일 수 있습니다. (Java의 Cloneable 인터페이스 활용)
interface Prototype extends Cloneable {
Prototype clone();
}
class Monster implements Prototype {
String type;
int health;
public Monster(String type, int health) {
this.type = type;
this.health = health;
}
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
public void status() {
System.out.println("몬스터: " + type + " / 체력: " + health);
}
}
public class Main {
public static void main(String[] args) {
Monster ogre = new Monster("오우거", 100);
Monster clonedOgre = (Monster) ogre.clone();
clonedOgre.health = 50; // 복제본의 상태 변경
ogre.status(); // 체력: 100
clonedOgre.status(); // 체력: 50
}
}