[디자인 패턴(Design Pattern)] 브릿지(Bridge)

업데이트:

카테고리:

태그:


브릿지 패턴이란?

브릿지 패턴은 구조 패턴 중의 하나로 구현부에서 추상층을 분리해 각자 독립적으로 확장할 수 있도록 구성하는 디자인 패턴이다.

장점

  • 추상층과 구현부를 독립적으로 확장 가능
  • 추상층을 구현한 클래스를 바꾸어도 클라이언트에는 영향을 끼치지 않음

구성

image

이미지 출처 : 위키피디아

  • Abstraction : 기본 기능만을 정의한 추상 클래스
  • RefindAbstraction : 확장된 기능을 가진 Abstraction의 하위 클래스
  • Implementor : 구현 클래스의 인터페이스를 정의
  • ConcreteImplementor : Implementor의 하위 클래스

예시 (Kotlin)

일단은 위의 구성에 있는 다이어그램대로 구현해보자.

우선 기능을 구현할 Implementor의 인터페이스를 정의한다.

interface Implementor {
    fun implementation()
}

Implementor을 상속받아 확장된 기능을 구현할 ConcreteImplementor들을 만든다.

class ConcreteImplementor1 : Implementor{
    override fun implementation() {
        println("Implementor1 action")
    }
}

class ConcreteImplementor2 : Implementor{
    override fun implementation() {
        println("Implementor2 action")
    }
}

이제 추상층을 나타낼 Abstraction 클래스를 만들어보자

abstract class Abstraction(
    private var implementor : Implementor
) {
    fun function(){
        implementor.implementation()
    }
}

추상층의 최상위에 있는 Abstraction이 implementor과 연결되는 다리(bridge)역할을 해줄것이다.

이제 확장된 기능을 가진 Abstraction의 하위 클래스 RefinedAbstraction들을 생성하자.

class RefinedAbstraction1(implementor: Implementor) : Abstraction(implementor){
    fun refinedAbstraction(){
        print("ra1 :")
        function()
    }
}

class RefinedAbstraction2(implementor: Implementor) : Abstraction(implementor){
    fun refinedAbstraction(){
        print("ra2 :")
        function()
    }
}

이제 다음 코드를 이용해 각각의 확장 기능이 잘 연결되었는지 확인한다.

fun main() {
    val ra1 = RefinedAbstraction1(ConcreteImplementor1())
    val ra2 = RefinedAbstraction2(ConcreteImplementor2())

    ra1.refinedAbstraction()
    ra2.refinedAbstraction()
}


출력

ra1 :Implementor1 action
ra2 :Implementor2 action