[디자인 패턴(Design Pattern)] 프로토타입(Prototype)

업데이트:

카테고리:

태그:


프로토타입 패턴이란?

프로토타입 패턴은 생성하려는 객체와 유사한 객체가 존재할 경우 그 원본 객체를 clone하여 새로운 객체를 생성하는 방식이다.

장점

  • 객체의 생성 비용이 클 경우 객체 생성의 비용을 줄일 수 있다.

예를 들어 DB로부터 데이터를 가져와 객체를 생성할 경우 clone을 하는 것 보다 훨씬 더 많은 비용이 들기 때문에 유사한 객체를 clone하는 편이 더 적은 비용으로 객체를 생성할 수 있다.

예시 (Kotlin)

clone()메소드는 Object클래스의 내장 함수로 얕은 복사(shallow copy)로 객체를 복사한다. 따라서 깊은 복사(deep copy)가 필요한 경우 clone()메소드를 재정의 해야한다.

data class Man(
    val name : String,
    val children : MutableList<Man> = mutableListOf()
) : Cloneable{
    public override fun clone(): Man {
        val newChildren = mutableListOf<Man>()
        children.forEach { newChildren.add(it.clone()) }
        return Man(name,newChildren)
    }
    fun print(){
        println(name)
        children.forEach { it.print() }
    }
}

다음의 코드를 통해 clone()메소드를 실행해 보자

val man1 = Man("Tom")
man1.children.add(Man("Jenny"))
man1.children.add(Man("mike"))
man1.children.add(Man("micheal"))

val man2 = man1.clone()

man1.print()
println()
man2.print()

출력 :

Tom
Jenny
mike
micheal

Tom
Jenny
mike
micheal

같은 객체가 복제됨을 확인할 수 있다.