중재자패턴 (1)

Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

오늘 살펴볼  Mediator 패턴은 Behavioral 패턴에 속합니다. 

 

Mediator Pattern Structure

 



전형적인 객체 구조는 아래와 같습니다.




  

패턴의 목적 ( Intent ) :  

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.


패턴이 나오게 된 동기 ( Motivation ) :

    We want to design reusable components, but dependencies between the potentially reusable pieces demonstrates the "spaghetti code" phenomenon. 개발자들은 보통 재사용 가능한 컴포넌트들을 만들고 싶어하지만 잠재적으로 재사용가능한 코드들의 의존성이 일명 "스파게티 코드"를 발생시키게 됩니다. 스파게티 코드라는 것은 거미줄처럼 뒤죽박죽 의존성이 존재하는 것을 의미합니다.

 

 

유닉스나 리눅스 시스템에 있는 사용자 퍼미션 시스템을 예로 들어보겠습니다. 한 사용자는 여러 그룹에 속해있을 수 있으며 한 그룹은 여러 사용자를 가질 수 있습니다. 아래 그림 처럼 말이죠. 


위 시스템을 구현한다고 해보자구요. 그럼 User 객체들과 Group객체들 사이에 연결고리가 있겠죠? 그 연결고리 때문에 User객체나 Group객체가 변경될 때 서로 영향을 미치게 될겁니다. 그러면 둘 사이의 관계만을 정의하는 객체를 따로 만들면 어떨 까요? User객체나 Group객체가 변경되어도 서로에게 영향을 미치게 될 일이 사라지게 됩니다. 또한, 수많은 관계들을 쉽게 관리할 수 있게 될 뿐아니라 수정하는 일도 쉬워질 겁니다. 

 

여기서 관계를 정의하는 객체를 중재자 객체라고 생각할 수 있습니다. 중재자 객체는 다음 역할들을 수행합니다. 

  1. encapsulates all interconnections
  2. acts as the hub of communication
  3. is responsible for controlling and coordinating the interactions of its clients
  4. promotes loose coupling by keeping objects from referring to each other explicitly


유용성 ( Applicability ) :

 

Use the Mediator pattern when

  • a set of objects communicate in well-defined but complex ways. The resulting inter dependencies are unstructured and difficult to understand.

  • reusing an object is difficult because it refers to and communicates with many other objects.

  • a behavior that's distributed between several classes should be customizable without a lot of subclassing.


등장 인물 ( Participants ) :

  • Mediator
    o
    defines an interface for communicating with Colleague objects.
  • ConcreteMediator
    o
    implements cooperative behavior by coordinating Colleague objects.
    o
    knows and maintains its colleagues.
  • Colleague classes
    o
    each Colleague class knows its Mediator object.
    o
    each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague.


원리 ( Collaborations ) :  

  • Colleagues send and receive requests from a Mediator object. The mediator implements the cooperative behavior by routing requests between the appropriate colleague(s).


패턴 사용법

  1. Identify a collection of interacting objects that would benefit from mutual decoupling.
  2. Encapsulate those interactions in the abstraction of a new class.
  3. Create an instance of that new class and rework all "peer" objects to interact with the Mediator only.
  4. Balance the principle of decoupling with the principle of distributing responsibility evenly.
  5. Be careful not to create a "controller" or "god" object.


패턴 사용의 장단점 ( Consequences ): 

The Mediator pattern has the following benefits and drawbacks:

  1. It limits subclassing. A mediator localizes behavior that otherwise would be distributed amongseveral objects. Changing this behavior requires subclassing Mediatoronly; Colleague classes can be reused as is.

  2. It decouples colleagues. A mediator promotes loose coupling between colleagues. You can vary and reuse Colleague and Mediator classes independently.

  3. It simplifies object protocols. A mediator replaces many-to-many interactions with one-to-many interactions between the mediator and its colleagues. One-to-many relationships are easier to understand, maintain, and extend.

  4. It abstracts how objects cooperate. Making mediation an independent concept and encapsulating it in an object lets you focus on how objects interact apart from their individual behavior. That can help clarify how objects interact in a system.

  5. It centralizes control. The Mediator pattern trades complexity of interaction for complexity in the mediator. Because a mediator encapsulates protocols, it can become more complex than any individual colleague. This can make the mediator itself a monolith that's hard to maintain.

관련 패턴들 :  

 

Facade differsfrom Mediator in that it abstracts a subsystem of objects to providea more convenient interface. Its protocol is uni-directional; thatis, Facade objects make requests of the subsystem classes but notvice versa. In contrast, Mediator enables cooperative behavior that colleague objects don't or can't provide, and the protocol is multi-directional.

Colleagues can communicate with the mediator using the Observer pattern.


추가 정보 :      

  • Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers. Command normally specifies a sender-receiver connection with a subclass. Mediator has senders and receivers reference each other indirectly. Observer defines a very decoupled interface that allows for multiple receivers to be configured at run-time.
  • Mediator and Observer are competing patterns. The difference between them is that Observer distributes communication by introducing "observer" and "subject" objects, whereas a Mediator object encapsulates the communication between other objects. We've found it easier to make reusable Observers and Subjects than to make reusable Mediators.
  • On the other hand, Mediator can leverage Observer for dynamically registering colleagues and communicating with them.
  • Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communication between colleague objects, it routinely "adds value", and it is known/referenced by the colleague objects (i.e. it defines a multidirectional protocol). In contrast, Facade defines a simpler interface to a subsystem, it doesn't add new functionality, and it is not known by the subsystem classes (i.e. it defines a unidirectional protocol where it makes requests of the subsystem classes but not vice versa).

 

출처 :  http://sourcemaking.com/design_patterns/mediator

Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )