minstudio

프로토타입 패턴 (Prototype)

프로토타입 패턴(Prototype Pattern)은 원본 객체를 복제(Clone)하여 새로운 객체를 생성하는 패턴입니다.

객체를 new 키워드로 생성하고 DB 조회 등을 통해 복잡하게 초기화하는 과정이 매우 비쌀(Cost가 높을) 때, 이미 완벽하게 세팅된 '프로토타입 객체'를 하나 만들어두고 이를 메모리 상에서 통째로 복사해서 사용하면 성능을 극적으로 높일 수 있습니다. (Java의 Cloneable 인터페이스 활용)

🧬 Prototype: 비용이 비싼 초기화 대신 메모리 복제 원본 몬스터 객체 DB에서 스탯 100개 로딩 완료 3D 메쉬 데이터 로딩 완료 Clone() 지원 복제 (0.01ms) 클론 몬스터 1 클론 몬스터 2 클론 몬스터 3 new 연산과 DB조회 없이, 메모리 복제만으로 군단을 순식간에 생성합니다.
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
    }
}
프로토타입 패턴 (Prototype) | Minstudio