Mediator Vs Observer Object-Oriented Design Patterns

前端 未结 8 632
一向
一向 2020-11-29 17:48

I have been reading the Gang Of Four, in order to solve some of my problems and came across the Mediator pattern.

I had earlier use

相关标签:
8条回答
  • 2020-11-29 18:15

    Although both of them are used for organised way of telling about state changes, they're slightly different structurally and semantically IMO.

    Observer is used to broadcast a state change of a particular object, from the object itself. So the change happens in the central object that is also responsible for signalling it. However, in Mediator, state change can happen in any object but it's broadcasted from a mediator. So there's a difference in the flow. But, I don't think this affects our code behaviour. We can use one or another to achieve the same behaviour. On the other hand, this difference might have some affects on conceptual understanding of the code.

    See, the primary purpose of using patterns is rather to create a common language between developers. So, when I see a mediator, I personally understand multiple elements trying to communicate over a single broker/hub to reduce communication noise (or to promote SRP) and each object is equally important in terms of having the ability of signalling a state change. For example, think of multiple aircrafts approaching to an airport. Each should communicate over the pylon (mediator) rather than communicating with each other. (Think of 1000 aircrafts communicating with each other when landing - that would be a mess)

    However, when I see an observer, it means there're some state changes I might be care about and should register/subscribe to listen particular state changes. There's a central object responsible for signalling state changes. For example, if I care about a specific airport on my way from A to B, I can register to that airport to catch some events broadcasted like if there's an empty runway or something like that.

    Hope it's clear.

    0 讨论(0)
  • 2020-11-29 18:27

    These patterns are used in different situations:

    The mediator pattern is used when you have two sub-systems with some dependency and one of them is due for a change, and since you might not want to change the system that depends on the other, you may want to introduce a mediator which will decouple the dependency between them. That way, when one of the sub-systems changes, all you have to do is to update the mediator.

    The observer pattern is used when a class wants to allow other classes to register themselves and receive notifications upon events, e. g. ButtonListener etc.

    Both of these patterns allow for lesser coupling, but are quite different.

    0 讨论(0)
  • 2020-11-29 18:27

    @cdc explained the difference in intent excellently.

    I will add some more info on top it.

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

    Mediator: Centralize the communication between set of objects, created from a particular class.

    Structure of Mediator pattern from dofactory:

    Mediator: Defines an interface for communication between Colleagues.

    Colleague: Is an abstract class, which defines the events to be communicated between Colleagues

    ConcreteMediator: Implements cooperative behavior by coordinating Colleague objects and maintains its colleagues

    ConcreteColleague: Implements the notification operations received through Mediator, which has been generated by other Colleague

    One real world example:

    You are maintaining a network of computers in Mesh topology. If a new computer is added Or existing computer is removed, all other computers in that network should know about these two events.

    Let's see how Mediator pattern 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);
        }
    }
    

    output:

    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:

    1. Eagle is added to network at first through register event. No notifications to any other colleagues since Eagle is the first one.
    2. When Ostrich is added to the network, Eagle is notified : Line 1 of output is rendered now.
    3. When Penguin is added to network, both Eagle and Ostrich have been notified : Line 2 and Line 3 of output is rendered now.
    4. When Eagle left the network through unregister event, both Ostrich and Penguin have been notified. Line 4 and Line 5 of output is rendered now.
    0 讨论(0)
  • 2020-11-29 18:28

    Observer

    1. Without

    • Client1: Hey Subject, when do you change?

    • Client2: When did you change Subject? I have not noticed!

    • Client3: I know that Subject has changed.

    2. With

    • Clients are silent.
    • Some time later ...
    • Subject: Dear clients, I have changed!

    Mediator

    1. Without

    • Client1: Hey Taxi1, take me some where.
    • Client2: Hey Taxi1, take me some where.
    • Client1: Hey Taxi2, take me some where.
    • Client2: Hey Taxi2, take me some where.

    2. With

    • Client1: Hey TaxiCenter, please take me a Taxi.
    • Client2: Hey TaxiCenter, please take me a Taxi.
    0 讨论(0)
  • 2020-11-29 18:29

    The Observer pattern: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

    The Mediator pattern: 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.

    Source: dofactory

    Example:

    The observer pattern: Class A, can have zero or more observers of type O registered with it. When something in A is changed it notifies all of the observers.

    The mediator pattern: You have some number of instances of class X (or maybe even several different types:X, Y & Z), and they wish to communicate with each other (but you don't want each to have explicit references to each other), so you create a mediator class M. Each instance of X has a reference to a shared instance of M, through which it can communicate with the other instances of X (or X, Y and Z).

    0 讨论(0)
  • 2020-11-29 18:30

    In the original book that coined the terms Observer and Mediator, Design Patterns, Elements of Reusable Object-Oriented Software, it says that the Mediator pattern can be implemented by using the observer pattern. However it can also be implemented by having Colleagues (which are roughly equivalent to the Subjects of the Observer pattern) have a reference to either a Mediator class or a Mediator interface.

    There are many cases when you would want to use the observer pattern, they key is that an object should not know what other objects are observing it's state.

    Mediator is a little more specific, it avoids having classes communicate directly but instead through a mediator. This helps the Single Responsibility principle by allowing communication to be offloaded to a class that just handles communication.

    A classic Mediator example is in a GUI, where the naive approach might lead to code on a button click event saying "if the Foo panel is disabled and Bar panel has a label saying "Please enter date" then don't call the server, otherwise go ahead", where with the Mediator pattern it could say "I'm just a button and have no earthly business knowing about the Foo panel and the label on the Bar panel, so I'll just ask my mediator if calling the server is O.K. right now."

    Or, if Mediator is implemented using the Observer pattern the button would say "Hey, observers (which would include the mediator), my state changed (someone clicked me). Do something about it if you care". In my example that probably makes less sense then directly referencing the mediator, but in many cases using the Observer pattern to implement Mediator would make sense, and the difference between Observer and Mediator would be more one of intent than a difference in the code itself.

    0 讨论(0)
提交回复
热议问题