Object Oriented Vs Observer Mediator Design Patterns

I read Gang Of Four to solve some of my problems and came across a Mediator .

I used to use Observer in my projects to create some GUI application. I am a little confused, because I do not see much difference between them. I looked to find the difference, but could not find a suitable answer for my request.

Can someone help me distinguish between the two with a good example that clearly demarcates the two?

+81
oop design-patterns mediator observer-pattern
Feb 10 2018-12-12T00:
source share
8 answers

Observer Pattern: Defines a one-to-many relationship between objects, so when one object changes, all its dependents are notified and updated automatically.

Reseller scheme: Define an object that encapsulates the interaction of the object. The mediator promotes a free connection, preventing direct access of objects to each other, and allows you to independently change their interaction.

Source: dofactory

Example:

Observer Scheme: Class A, may have zero or more type O observers registered with it. When something in changes, it notifies all observers.

Plectrum scheme: You have several instances of class X (or perhaps even several different types: X, Y, and Z), and they want to communicate with each other (but you do not want each to have explicit links to each other) , so you create an intermediary class M. Each instance of X has a reference to a common instance of M through which it can communicate with other instances of X (or X, Y, and Z).

+94
Feb 10 2018-12-12T00:
source share

The original book, which used the terms Observer and Mediator, Design Patterns, Elements of Reusable Object-Oriented Software, states that the Mediator pattern can be implemented using an observer pattern. However, this can also be implemented if Colleagues (which are roughly equivalent to Observer template objects) have a reference to a mediation class or mediation interface.

There are many cases where you would like to use the observer pattern; they indicate that the object should not know that other objects are observing the state.

The mediator is a little more specific, it avoids the classes being bound directly, but instead through the mediator. This helps the principle of single responsibility, allowing you to disconnect the link to a class that simply handles the link.

A classic intermediary example is in the graphical interface, where a naive approach can lead to event code with a click of a button that says: "If the Foo panel is disabled, and the panel has a label" Please enter a date ", then do not call the server, in otherwise go ahead ", where with the help of the template" Reseller "he could say" I’m just a button and I don’t have any earth business knowing about the Foo panel and the shortcut on the Bar panel, so I’ll just ask my intermediary if the server is called in order."

Or, if the Mediator is implemented using the Observer template, the button will indicate: “Hey, observers (which will include an intermediary), my state has changed (someone clicked me). Do something if you need to.” In my example, which probably makes less sense and then directly refers to the mediator, but in many cases using the Observer pattern to implement the mediator makes sense, and the difference between Observer and Mediator will be more solid than the difference in the code itself.

+32
Feb 10 '12 at 18:44
source share

Observer

1. Without

  • Client1 : Hey Subject , when do you change?

  • Customer 2 . When did you change the theme ? I did not notice!

  • Customer 3 . I know that Theme has changed.

2. C

  • Customers do not work.
  • Over time...
  • Subject : Dear customers , I have changed!



Mediator

1. Without

  • Client1 : hi Taxi1 , take me somewhere.
  • Client2 : hi Taxi1 , take me somewhere.
  • Client1 : Hey Taxi2 , take me where to.
  • Client2 : Hey Taxi2 , take me where to.

2. C

  • Client1 : Hey TaxiCenter , please take Taxi .
  • Client2 : Hi TaxiCenter , please accept me Taxi .
+29
May 27 '16 at 23:41
source share

These patterns are used in different situations:

The mediator template is used when you have two subsystems with some dependency, and one of them is related to the change, and since you may not want to change the system, which depends on the other, you may want to introduce a mediator that will separate the dependency between them. Thus, when one of the subsystems changes, all you have to do is update the pick.

The observer pattern is used when a class wants to allow other classes to register and receive event notifications, for example. ButtonListener etc.

Both of these patterns allow less connection, but are completely different.

+13
Feb 10 2018-12-12T00:
source share

Although both of them are used for an organized way of talking about state changes, they are slightly different structurally and semantically IMO.

The observer is used to transmit the state changes of a particular object from the object itself. Thus, the change occurs in the central object, which is also responsible for its signaling. However, in the Intermediary, a state change can occur in any object, but it is transmitted from the intermediary. So there is a difference in flow. But I do not think that this affects the behavior of our code. We can use this or that to achieve the same behavior. On the other hand, this difference may have some effect on the conceptual understanding of the code.

You see, the main purpose of using templates is to create a common language between developers. So, when I see the intermediary, I personally understand several elements trying to exchange data through one broker / hub in order to reduce communication noise (or promote SRP), and each object is equally important in terms of the ability to signal a state change. For example, think of several planes approaching an airport. Everyone should communicate through the pylon (intermediary), and not communicate with each other. (Think of the 1000 aircraft that communicate with each other when landing)

However, when I see an observer, this means that there are some state changes that I could take care of and have to register / sign in order to listen to certain state changes. There is the central object responsible for signaling state changes. For example, if I take care of a specific airport on the way from A to B, I can check in at that airport to track some events, for example, if there is an empty runway or something like that.

Hope this is clear.

+5
Jan 05 '17 at 11:05
source share

@cdc explained the difference in intent perfectly.

I will add some more information about this.

Observer : Enables notification of an event in one object with a different set of objects (instances of different classes)

Mediator : Centralize the relationship between many objects created from a particular class.

The structure of the reseller template from dofactory :

enter image description here

Mediator: defines the interface for communication between colleagues.

Colleague: It is an abstract class that defines events that will be shared between colleagues.

ConcreteMediator: implements collaborative behavior by coordinating Colleague objects and supporting colleagues.

ConcreteColleague: implements notification operations received through an intermediary that was generated by another colleague

One example in the real world:

You maintain a network of computers in the Mesh topology. If a new computer is added or an existing computer is deleted, all other computers on this network should be aware of these two events.

Let's see how the Mediator template fits into it.

Code snippet:

import java.util.List; import java.util.ArrayList; /* Define the contract for communication between Colleagues. Implementation is left to ConcreteMediator */ interface Mediator{ public void register(Colleague colleague); public void unregister(Colleague colleague); } /* Define the contract for notification events from Mediator. Implementation is left to ConcreteColleague */ abstract class Colleague{ private Mediator mediator; private String name; public Colleague(Mediator mediator,String name){ this.mediator = mediator; this.name = name; } public String toString(){ return name; } public abstract void receiveRegisterNotification(Colleague colleague); public abstract void receiveUnRegisterNotification(Colleague colleague); } /* Process notification event raised by other Colleague through Mediator. */ class ComputerColleague extends Colleague { private Mediator mediator; public ComputerColleague(Mediator mediator,String name){ super(mediator,name); } public void receiveRegisterNotification(Colleague colleague){ System.out.println("New Computer register event with name:"+colleague+ ": received @"+this); // Send further messages to this new Colleague from now onwards } public void receiveUnRegisterNotification(Colleague colleague){ System.out.println("Computer left unregister event with name:"+colleague+ ":received @"+this); // Do not send further messages to this Colleague from now onwards } } /* Act as a central hub for communication between different Colleagues. Notifies all Concrete Colleagues on occurrence of an event */ class NetworkMediator implements Mediator{ List<Colleague> colleagues = new ArrayList<Colleague>(); public NetworkMediator(){ } public void register(Colleague colleague){ colleagues.add(colleague); for (Colleague other : colleagues){ if ( other != colleague){ other.receiveRegisterNotification(colleague); } } } public void unregister(Colleague colleague){ colleagues.remove(colleague); for (Colleague other : colleagues){ other.receiveUnRegisterNotification(colleague); } } } public class MediatorPatternDemo{ public static void main(String args[]){ Mediator mediator = new NetworkMediator(); ComputerColleague colleague1 = new ComputerColleague(mediator,"Eagle"); ComputerColleague colleague2 = new ComputerColleague(mediator,"Ostrich"); ComputerColleague colleague3 = new ComputerColleague(mediator,"Penguin"); mediator.register(colleague1); mediator.register(colleague2); mediator.register(colleague3); mediator.unregister(colleague1); } } 

exit:

 New Computer register event with name:Ostrich: received @Eagle New Computer register event with name:Penguin: received @Eagle New Computer register event with name:Penguin: received @Ostrich Computer left unregister event with name:Eagle:received @Ostrich Computer left unregister event with name:Eagle:received @Penguin 

Explanation:

  • Eagle is added to the network first through a registration event. No notifications to other colleagues since Eagle is the first.
  • When Ostrich is added to the network, Eagle is notified: line 1 of output is now output.
  • When the penguin was added to the network, both Eagle and Ostrich were notified: now line 2 and line 3 are displayed.
  • When the Eagle left the net through an unregistered event, both ostriches and penguins were notified. Now lines 4 and line 5 are displayed.
+4
Aug 08 '16 at 15:39
source share

Let's look at an example: consider how you want to create two applications:

  1. Chat application.
  2. Ambulance operator app.



mediator

Once you create the chat application, you will select the mediator design template.

  • People can join and leave the chat at any time, so it makes no sense to keep a direct link between two people in the chat.
  • We still need to facilitate communication between the two people and allow them to chat.

Why do we prefer a mediator ? just take a look at its definition:

Using the mediator template, the connection between objects is encapsulated inside an intermediary object. Objects no longer communicate directly with each other, but instead communicate through an intermediary. This reduces the relationship between communicating objects, thereby reducing traction.

How does magic work? First, we will create a chat broker and make object objects for it, so it will have a two-way connection with each person (a person can send a message using the chat broker because he has access to it, and the chat broker will access the received object method -man also causes him access to it)

 function Person(name) { let self = this; this._name = name; this._chat = null; this._receive(from, message) { console.log("{0}: '{1}'".format(from.name(), message)); } this._send(to, message) { this._chat.message(this, to, message); } return { receive: (from, message) => { self._receive(from, message) }, send: (to, message) => { self._send(to, message) }, initChat: (chat) => { this._chat = chat; }, name: () => { return this._name; } } } function ChatMediator() { let self = this; this._persons = []; return { message: function (from, to, message) { if (self._persons.indexOf(to) > -1) { self._persons[to].receive(from, message); } }, register: function (person) { person.initChat(self); self._persons.push(person); } unRegister: function (person) { person.initChat(null); delete self._persons[person.name()]; } } }; //Usage: let chat = new ChatMediator(); let colton = new Person('Colton'); let ronan = new Person('Ronan'); chat.register(colton); chat.register(ronan); colton.send(colton, 'Hello there, nice to meet you'); ronan.send(ronan, 'Nice to meet you to'); colton.send(colton, 'Goodbye!'); chat.unRegister(colton); 



observer

When you create the 911 challenge application, you select the observer design template.

  • Each ambulance observer object wants to be informed when there is an emergency condition, so it can manage the address and give help.
  • observable emergency operator keeps a link to each of the ambulance observers and notifies them when help is needed (or generating an event).

Why would we prefer an observer ? just take a look at its definition:

An object called a subject maintains a list of its dependents, called observers, and automatically notifies them of any state changes, usually by calling one of its methods.

 function AmbulanceObserver(name) { let self = this; this._name = name; this._send(address) { console.log(this._name + ' has been sent to the address: ' + address); } return { send: (address) => { self._send(address) }, name: () => { return this._name; } } } function OperatorObservable() { let self = this; this._ambulances = []; return { send: function (ambulance, address) { if (self._ambulances.indexOf(ambulance) > -1) { self._ambulances[ambulance].send(address); } }, register: function (ambulance) { self._ambulances.push(ambulance); } unRegister: function (ambulance) { delete self._ambulances[ambulance.name()]; } } }; //Usage: let operator = new OperatorObservable(); let amb111 = new AmbulanceObserver('111'); let amb112 = new AmbulanceObserver('112'); operator.register(amb111); operator.register(amb112); operator.send(amb111, '27010 La Sierra Lane Austin, MN 000'); operator.unRegister(amb111); operator.send(amb112, '97011 La Sierra Lane Austin, BN 111'); operator.unRegister(amb112); 

Differences:

  1. mediator chat mediator has two-way communication between objects of persons (sending and receiving), where the observable operator has only one-way communication (he informs the ambulance observer about control and completion).
  2. mediator chat mediator can cause people’s objects to interact between them (even if it’s not a direct connection) first aid observers only record observable operator events.
  3. Each object of the object has a link to the chat mediator , and the chat mediator maintains a link to each person. By observing that the ambulance observer does not pay attention to the observable operator, only the observable operator maintains a link to each ambulance observer .
+3
Jul 15 '18 at 18:02
source share

How about this explanation Technically, both Observer and Mediator are the same and are used to provide an unbound way of linking components, but the usage is different.

While obeserver notifies the signed components of the status of the changes (for example, creating a new db record), the mediator manages the registered components to do something with the business logic flow (sending an email to the user to reset the password).

observer

  • Notification users are responsible for subscribing to receive notifications
  • Notification processing is not part of the business flow

mediator

  • Explicit registration required to connect the "publisher" and the "consumers",
  • Notification processing is part of a specific business stream.
0
May 23 '18 at 8:39
source share



All Articles