본문 바로가기

PROGRAMMING/Design Pattern

[GoF] 브릿지 (Bridge) 패턴

브릿지 (Bridge) 패턴 구조 패턴

클래스의 구현 계층과 추상 계층을 분리하여 각자의 독립적인 변형을 용이하게 합니다.



객체 지향 프로그래밍에 있어 클래스의 상속이란 다형성의 의미 그 자체를 담는다. 그렇기에 프로그래머는 수 많은 이유로 클래스의 상속을 통해 다형성을 구현하는데, 그 이유를 분류하자면 두 가지 의미로 귀결된다: 상위 클래스의 기능을 확장하기 위해 상속하여 추상 계층을 형성하는 것과, 상위 클래스의 기능을 구현하기 위해 상속하여 구현 계층을 형성할 수가 있다. 그러나, 이 두가지 의도로 클래스를 복합적으로 상속해나갈 경우, 추상 계층과 구현 계층이 뒤섞여 확장하는데에 어려움이 발생할 것이다.

그래서 브릿지 패턴은 이 두 계층을 개별적인 클래스로 나누게 되며, 교량이 두 지점을 잇듯이 추상 계층이 구현 계층을 참조하여 연결한다. 그리하여 추상 계층과 구현 계층은 각자 독립적으로 확장할 수 있게 되고, 추상 계층은 구현 계층의 인터페이스를 가지고 구현 계층에 대한 지시를 정의하게 되어 구현에 대한 의존성을 분리하였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
public class Bridge
{
    public interface IAbstraction
    {
        void Operation();
    }
 
    public class AbstractionA : IAbstraction
    {
        private IImplementor _implementor;
 
        public AbstractionA(IImplementor implementor)
        {
            _implementor = implementor;
        }
 
        public void Operation()
        {
            _implementor.OperationImpA();
        }
    }
 
    public class AbstractionB : IAbstraction
    {
        private IImplementor _implementor;
 
        public AbstractionB(IImplementor implementor)
        {
            _implementor = implementor;
        }
 
        public void Operation()
        {
            _implementor.OperationImpB();
        }
    }
 
    public interface IImplementor
    {
        void OperationImpA();
        void OperationImpB();
    }
 
    public class ImplementorA : IImplementor
    {
        public void OperationImpA()
        {
            Console.WriteLine("Operating A in ImplementerA");
        }
 
        public void OperationImpB()
        {
            Console.WriteLine("Operating B in ImplementerA");
        }
    }
 
    public class ImplementorB : IImplementor
    {
        public void OperationImpA()
        {
            Console.WriteLine("Operating A in ImplementerB");
        }
 
        public void OperationImpB()
        {
            Console.WriteLine("Operating B in ImplementerB");
        }
    }
 
    public static void Main(string[] args)
    {
        IAbstraction[] abstractions = new IAbstraction[]
        {
           new AbstractionA(new ImplementorA()),
           new AbstractionA(new ImplementorB()),
           new AbstractionB(new ImplementorA()),
           new AbstractionB(new ImplementorB()),
       };
 
        foreach (IAbstraction abstraction in abstractions)
        {
            abstraction.Operation();
        }
    }
}
cs

1
2
3
4
5
Operating A in ImplementerA
Operating A in ImplementerB
Operating B in ImplementerA
Operating B in ImplementerB
Press any key to continue . . .
cs