[kotlin] 브리지 디자인 패턴과 코틀린

브리지 디자인 패턴은 구조적인 디자인 패턴 중 하나이다. 이 패턴은 추상화된 인터페이스와 구현부를 분리시킴으로써, 두 가지를 독립적으로 변형할 수 있게 한다.

브리지 패턴의 예제

// Abstraction
interface DrawingAPI {
    fun drawCircle(x: Int, y: Int, radius: Int)
}

// Concrete Implementor
class DrawingAPI1 : DrawingAPI {
    override fun drawCircle(x: Int, y: Int, radius: Int) {
        println("API1.circle at $x:$y radius $radius")
    }
}

// Refined Abstraction
abstract class Shape(protected val drawingAPI: DrawingAPI) {
    abstract fun draw()
    abstract fun resizeByPercentage(pct: Double)
}

// Concrete Abstraction
class CircleShape(private val x: Int, private val y: Int, private var radius: Int, drawingAPI: DrawingAPI) : Shape(drawingAPI) {

    override fun draw() {
        drawingAPI.drawCircle(x, y, radius)
    }

    override fun resizeByPercentage(pct: Double) {
        radius = (radius * (1 + pct / 100)).toInt()
    }

}

위의 코드는 브리지 패턴을 코틀린으로 구현한 예제이다.

브리지 디자인 패턴의 장점

브리지 디자인 패턴은 객체지향 프로그래밍에서 유연한 구조를 만들어준다. 코틀린의 인터페이스와 클래스를 이용하면 쉽게 브리지 패턴을 구현할 수 있다.

참고 자료

  1. 브리지 디자인 패턴 - 위키피디아
  2. Gamma, E. et al. (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley.