Sangil's blog

https://github.com/ChoiSangIl Admin

FlyweightPattern in kotlin with ChatGPT DEV / WEB

2023-03-05 posted by sang12


세상이 무섭게 변하는거 같다.
FlyweightPattern 코틀린 예제로 보여줘~ 라고하면 뚝딱 예제가 나온다

FlyweightPattern 은 특정 객체를 사용할때 마다 생성하지 않고
이미 만들어져있거나 없으면 만들어서 리턴해주는 방법이며
Flyweight이라는 용어처럼 리소스를 세이브할 수 있는 패턴이다.
일반적으로는 예제를 보면 이해가 되겠지만 다양한 방법으로 활용할 수 있지 않을까 싶다.

Chat GPT가 만들어준 FlyweightPattern

package pattern

interface Shape {
    fun draw(x: Int, y: Int)
}

class Circle(private val color: String) : Shape {
    override fun draw(x: Int, y: Int) {
        println("Drawing a $color circle at ($x, $y)")
    }
}

class ShapeFactory {
    private val circleMap = mutableMapOf<String, Shape>()

    fun getCircle(color: String): Shape {
        var circle = circleMap[color]

        if (circle == null) {
            circle = Circle(color)
            circleMap[color] = circle
            println("Creating a $color circle")
        } else {
            println("Reusing a $color circle")
        }

        return circle
    }
}

fun main() {
    val factory = ShapeFactory()

    val redCircle1 = factory.getCircle("red")
    redCircle1.draw(10, 10)

    val blueCircle1 = factory.getCircle("blue")
    blueCircle1.draw(20, 20)

    val redCircle2 = factory.getCircle("red")
    redCircle2.draw(30, 30)

    val blueCircle2 = factory.getCircle("blue")
    blueCircle2.draw(40, 40)
}

REPLY