Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Mediator pattern

From Wikipedia, the free encyclopedia
Not to be confused withBroker pattern.
Software architecture design pattern

Insoftware engineering, themediator pattern defines an object thatencapsulates how a set of objects interact. This pattern is considered to be abehavioral pattern due to the way it can alter the program's running behavior.

In object-oriented programming, programs often consist of manyclasses.Business logic andcomputation are distributed among these classes. However, as more classes are added to a program, especially duringmaintenance and/orrefactoring, the problem ofcommunication between these classes may become more complex. This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes.

With the mediator pattern, communication between objects is encapsulated within amediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducingcoupling.

Overview

[edit]

The mediator[1] design pattern is one of the twenty-three well-knowndesign patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

Problems that the mediator design pattern can solve

[edit]

Source:[2]

  • Tight coupling between a set of interacting objects should be avoided.
  • It should be possible to change the interaction between a set of objects independently.

Defining a set of interacting objects by accessing and updating each other directly is inflexible because it tightly couples the objects to each other and makes it impossible to change the interaction independently from (without having to change) the objects.And it stops the objects from being reusable and makes them hard to test.

Tightly coupled objects are hard to implement, change, test, and reuse because they refer to and know about many different objects.

Solutions described by the mediator design pattern

[edit]
  • Define a separate (mediator) object that encapsulates the interaction between a set of objects.
  • Objects delegate their interaction to a mediator object instead of interacting with each other directly.

The objects interact with each other indirectly through a mediator object that controls and coordinates the interaction.

This makes the objectsloosely coupled. They only refer to and know about their mediator object and have no explicit knowledge of each other.

See also the UML class and sequence diagram below.

Definition

[edit]

The essence of the mediator pattern is to "define an object that encapsulates how a set of objects interact". It promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to be varied independently.[3][4] Client classes can use the mediator to send messages to other clients, and can receive messages from other clients via an event on the mediator class.

Structure

[edit]

UML class and sequence diagram

[edit]
A sample UML class and sequence diagram for the mediator design pattern.[5]

In the aboveUMLclass diagram, theColleague1 andColleague2 classes do not refer to (and update) each other directly.Instead, they refer to the commonMediator interface for controlling and coordinating interaction (mediate()), which makes them independent from one another with respect to how the interaction is carried out.TheMediator1 class implements the interaction betweenColleague1 andColleague2.

TheUMLsequence diagram shows the run-time interactions. In this example, aMediator1 object mediates (controls and coordinates) the interaction betweenColleague1 andColleague2 objects.

Assuming thatColleague1 wants to interact withColleague2 (to update/synchronize its state, for example),Colleague1 callsmediate(this) on theMediator1 object, which gets the changed data fromColleague1 and performs anaction2() onColleague2.

Thereafter,Colleague2 callsmediate(this) on theMediator1 object, which gets the changed data fromColleague2 and performs anaction1() onColleague1.

Class diagram

[edit]
The mediator behavioural design pattern
Participants

Mediator - defines the interface for communication betweenColleague objects

ConcreteMediator - implements the mediator interface and coordinates communication betweenColleague objects. It is aware of all of theColleagues and their purposes with regards to inter-communication.

Colleague - defines the interface for communication with otherColleagues through itsMediator

ConcreteColleague - implements the Colleague interface and communicates with otherColleagues through itsMediator

Example

[edit]

C#

[edit]

The mediator pattern ensures that components areloosely coupled, such that they do not call each other explicitly, but instead do so through calls to a mediator. In the following example, the mediator registers all Components and then calls theirSetState methods.

namespaceWikipedia.Examples;usingSystem;interfaceIComponent{voidSetState(objectstate);}classComponent1:IComponent{internalvoidSetState(objectstate){thrownewNotImplementedException();}}classComponent2:IComponent{internalvoidSetState(objectstate){thrownewNotImplementedException();}}// Mediates the common tasksclassMediator{internalIComponentComponent1{get;set;}internalIComponentComponent2{get;set;}internalvoidChangeState(objectstate){this.Component1.SetState(state);this.Component2.SetState(state);}}

A chat room could use the mediator pattern, or a system where many ‘clients’ each receive a message each time one of the other clients performs an action (for chat rooms, this would be when each person sends a message). In reality using the mediator pattern for a chat room would only be practical when used withremoting. Using raw sockets would not allow for thedelegatecallbacks (people subscribed to the Mediator class’ MessageReceived event).

namespaceWikipedia.Examples;usingSystem;publicdelegatevoidMessageReceivedEventHandler(stringmessage,stringsender);publicclassMediator{publiceventMessageReceivedEventHandlerMessageReceived;publicvoidSend(stringmessage,stringsender){if(MessageReceived!=null){Console.WriteLine(f"Sending '{message}' from {sender}");MessageReceived(message,sender);}}}publicclassPerson{privateMediator_mediator;publicPerson(Mediatormediator,stringname){Name=name;_mediator=mediator;_mediator.MessageReceived+=newMessageReceivedEventHandler(Receive);}publicstringName{get;set;}privatevoidReceive(stringmessage,stringsender){if(sender!=Name){Console.WriteLine(f"{Name} received '{message}' from {sender}");}}publicvoidSend(stringmessage){_mediator.Send(message,Name);}}

Java

[edit]

In the following example, aMediator object controls the values of severalStorage objects, forcing the user code to access the stored values through the mediator. When a storage object wants to emit an event indicating that its value has changed, it also goes back to the mediator object (via the methodnotifyObservers) that controls the list of the observers (implemented using theobserver pattern).

packageorg.wikipedia.examples;importjava.util.HashMap;importjava.util.Optional;importjava.util.concurrent.CopyOnWriteArrayList;importjava.util.function.Consumer;classStorage<T>{Tvalue;TgetValue(){returnvalue;}voidsetValue(Mediator<T>mediator,StringstorageName,Tvalue){this.value=value;mediator.notifyObservers(storageName);}}classMediator<T>{privatefinalHashMap<String,Storage<T>>storageMap=newHashMap<>();privatefinalCopyOnWriteArrayList<Consumer<String>>observers=newCopyOnWriteArrayList<>();publicvoidsetValue(StringstorageName,Tvalue){Storagestorage=storageMap.computeIfAbsent(storageName,name->newStorage<>());storage.setValue(this,storageName,value);}publicOptional<T>getValue(StringstorageName){returnOptional.ofNullable(storageMap.get(storageName)).map(Storage::getValue);}publicvoidaddObserver(StringstorageName,Runnableobserver){observers.add(eventName->{if(eventName.equals(storageName)){observer.run();}});}voidnotifyObservers(StringeventName){observers.forEach(observer->observer.accept(eventName));}}publicclassMediatorDemo{publicstaticvoidmain(String[]args){Mediator<Integer>mediator=newMediator<>();mediator.setValue("Bob",20);mediator.setValue("Alice",24);mediator.getValue("Alice").ifPresent(age->System.out.printf("Age for Alice: %d\n",age));mediator.addObserver("Bob",()->{System.out.printf("New age for Bob: %s\n",mediator.getValue("Bob").orElseThrow(RuntimeException::new));});mediator.setValue("Bob",21);}}

See also

[edit]

References

[edit]
  1. ^Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994).Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 273ff.ISBN 0-201-63361-2.{{cite book}}: CS1 maint: multiple names: authors list (link)
  2. ^Franke, Günther."The Mediator design pattern - Problem, Solution, and Applicability".w3sDesign. Retrieved2017-08-12.
  3. ^Gamma, Erich; Helm, Richard;Johnson, Ralph;Vlissides, John (1994).Design Patterns.Addison-Wesley.ISBN 0-201-63361-2.
  4. ^"Mediator Design Pattern".SourceMaking.
  5. ^Franke, Günther."The Mediator design pattern - Structure and Collaboration".w3sDesign. Retrieved2017-08-12.

External links

[edit]
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also
Retrieved from "https://en.wikipedia.org/w/index.php?title=Mediator_pattern&oldid=1320458461"
Category:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp