본문 바로가기

개발/Etc

[Design Pattern] Bridge Pattern

Bridge Pattern 은 Structural Patterns(구조 패턴)에 속한다.


Bridge Pattern

구현부에서 추상층을 분리하여 각자 독립적으로 변형 가능하고 확장 가능하도록 하는 패턴으로, 기능과 구현에 대해서 두 개의 별도 클래스로 구현한다.

기능 클래스 계층 : A 상위 클래스를 상속받는 B 하위 클래스에서 새로운 기능을 추가하는 계층이다.
구현 클래스 계층 : A 인터페이스(API)를 구현한 B 객체가 존재할 경우 구현 클래스 계층이라고 한다.

Bridge Pattern UML

  • Abstraction(추상화) : 기능 클래스 계층의 상위 클래스로 기본 기능 정의만 한다.
  • RefinedAbstraction(개선된 추상화) : 기능 클래스 계층의 하위 클래스로 기능을 추가한다.
  • Implementor(구현자) : 구현 클래스 계층의 상위 클래스로 인터페이스 API를 규정한다.
  • Concrete Implementor(구체 구현자) : 구현 클래스 계층의 하위 클래스로 API를 정의한다. 

언제 쓰면 좋을까?

두 구체 클래스 간의 강한 결합을 제거하고 싶을 때 사용하면 좋다.

예시 코드

Abstraction - 어떤 기능을 이용할지 정의하고 멤버변수인 구현부를 통하여 기능을 동작시킨다.

public abstract class Shape {
    protected Draw draw;

    protected Shape(Draw draw) {
        this.draw = draw;
    }

    public abstract void draw();
}

RefinedAbstraction - 기본 기능을 재정의하고 구현을 가져와서 사용한다.

public class Circle extends Shape {
    private int radius, x, y;

    public Circle(int radius, int x, int y, Draw draw) {
        super(draw); //부모 클래스의 생성자 호출
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    @Override
    public void draw() {
    	//draw한테 구체적인 구현부를 위임한다.
        draw.drawCircle(radius, x, y);
    }
}

Implementor - 기본 기능을 구현할 수 있도록 규정한다.

public interface Draw {
    public void drawCircle(int radius, int x, int y);
}

Concrete Implementor - 기본 기능을 구현한다.

public class RedCircle implements Draw {
    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color : red, radius : " + radius + ", x : " + x + ", y : " + y + "]");
    }
}

Client

public class Main {
    public static void main(String[] args) {
        Shape redCircle = new Circle(10,100, 100, new RedCircle());
        redCircle.draw();
    }
}

//결과
Drawing Circle[ color : red, radius : 10, x : 100, y : 100]

장점

  • 두 계층을 분리함으로써 확장이 용이해진다.
  • 변경이 되어도 Client쪽에는 영향을 끼치지 않는다.

단점

  • 응집력 있는 클래스에 적용하면 코드가 더 복잡해 질 수 있다.

관련 패턴

  • Adapter Pattern : 인터페이스(API)가 서로 다른 클래스를 결합해준다.

'개발 > Etc' 카테고리의 다른 글

UUID type3, UUID type4 (JAVA)  (0) 2021.08.24
[Design Pattern] Observer Pattern  (0) 2021.08.11
[Design Pattern] Prototype Pattern  (0) 2021.08.07
[Design Pattern] 디자인 패턴 23 가지  (0) 2021.08.04