Façade vs. Mediator

2019-01-16 03:06发布

问题:

I've been researching the difference between these two patterns.

I understand that facade encapsulates access to a sub system and mediator encapsulates the interactions between components.

I understand that sub system components are not aware of the facade, where as components are obviously aware of the mediator.

I'm currently using a facade for encapsulating the method of retrieving configuration information, e.g. App.Config, user setting stored in SQL, Assembly info, etc, and a mediator for navigation between different windows forms.

However, most sites point out that the mediator “adds functionality”. What do they mean by this? How does mediator add functionality?

回答1:

...most sites point out that the mediator “adds functionality”...

The facade only exposes the existing functionality from a different perspective.

The mediator "adds" functionality because it combines different existing functionality to create a new one.

Take the following example:

You have a logging system. From that logging system you can either log to a file, to a socket, or to a database.

Using the facade design pattern you would "hide" all the relationships from existing functionality behind a single "interface" the one that the facade exposes.

Client code:

 Logger logger = new Logger();
 logger.initLogger("someLogger");
 logger.debug("message");

The implementation may involve the interaction of many objects. But at the end, the functionality already exists. Probably the "debug" method is implemented as follows:

Implementation:

 class Logger { 

      private LoggerImpl internalLogger;
      private LoggerManager manager;

      public void initLogger( String loggerName ) {
          this.internalLogger = manager.getLogger( loggerName ); 
      }

      public void debug( String message ) { 
          this.internalLogger.debug( message );
      }     
 }

The functionality already exist. The facade only hides it. In this hypothetical case, the LoggerManager handles the creation of the correct logger, and the LoggerImpl is a package private object that has the "debug" method. This way the Facade is not adding functionality it is just delegating to some existing objects.

In the other hand the mediator add the new functionality by combining different objects.

Same Client code:

 Logger logger = new Logger();
 logger.initLogger("someLogger");
 logger.debug("message");

Implementation:

 class Logger { 

      private java.io.PrintStream out;
      private java.net.Socket client;
      private java.sql.Connection dbConnection;
      private String loggerName;


      public void initLogger( String loggerName ) {
               this.loggerName = loggerName;
               if ( loggerName == "someLogger" ) { 
                    out = new PrintStream( new File("app.log"));
               } else if ( loggerName == "serverLog" ) { 
                    client = new Socket("127.0.0.1", 1234 );
               } else if( loggerName == "dblog") { 
                    dbConnection = Class.forName()... .
               }

      }

      public void debug( String message ) { 

               if ( loggerName == "someLogger" ) { 
                    out.println( message );
               } else if ( loggerName == "serverLog" ) { 
                    ObjectOutputStrewam oos = 
                           new ObjectOutputStrewam( client.getOutputStream());
                    oos.writeObject( message );
               } else if( loggerName == "dblog") { 
                    Pstmt pstmt = dbConnection.prepareStatment( LOG_SQL );
                    pstmt.setParameter(1, message );
                    pstmt.executeUpdate();
                    dbConnection.commit();
               }
      }
 }

In this code, the mediator is the one that contains the business logic to create the appropriate "channel" to log and also to make the log into that channel. The mediator is "creating" the functionality.

Of course, there are better ways to implement this using polymorphism, but the point here is to show how the mediator "adds" new functionality by combining existing functionality ( in my sample didn't show very much sorry ) but imagine the mediator, read from the database the remote host where to log, then creates a client and finally write to that client print stream the log message. This way the mediator would be "mediating" between the different objects.

Finally, the facade is an structural pattern, that is it describes the composition of the objects, while the mediator is an behavioral, that is , it describes the way the objects interact.

I hope this helps.



回答2:

I'm using mediator to add log file functionality.

It works like this:

  • Obj A tells the mediator it needs something done.
  • The mediator sends the message to various client objects.
  • Obj B does the thing Obj A needs, and sends an appropriate message back via the mediator.
  • Meanwhile, Obj C is also sent both messages by the mediator, and logs the results. That way, we can get user statistics from the log files.
  • Obj D could be an error checker as well, so that if Obj B responds that Obj A's request is impossible, Obj D could be the thing that reports that to the user. Errors can now be logged in a different file than regular activity, and could use some other means to behave (beeping, whatever) that Obj A shouldn't really concern itself with.


回答3:

under related patterns, gof says: Facade (185) differs from Mediator in that it abstracts a subsystem of objects to provide a more convenient interface. Its protocol is unidirectional; that is, Facade objects make requests of the subsystem classes but not vice versa. In contrast, Mediator enables cooperative behavior that colleague objects don't or can't provide, and the protocol is multidirectional.



回答4:

Take a simple analogy:

Facade: like a parking lot, when call

parkingLot.Out(car1);

mab be a simple chain works:

{
  car1.StartEngin();      
  attendant.charge();
  car1.driverOut();
}

Mediator: like traffic light.

There are interactions between light and car,

and cars are controlled by it's state.

I though maybe this is the mediator “adds functionality”


And about the definition:

Facade's Type: Structural

Mediator's Type: Behavioral

facade more concerned about the components were contained in the unified interface,

and mediator concern how a set of objects interact.



回答5:

I thought the distinction was directional: facade is a one-way communication between client and facade; mediator can be a two-way conversation, with messages flowing back and forth between the client and mediator.



回答6:

From the "Design Patterns" book, the KEY of the Mediator pattern is described as follows: "It (a mediator) acts as a HUB of communication for widgets (i.e., 'a' group of interdependent objects)."

In other words, a mediator object is the sole superobject that knows all other objects in a group of collaborating objects and how they should interact with each other. All other objects should interact with the mediator object, instead of each other.

In contrast, a facade is a "unified interface" for a set of interfaces in a subsystem - for use by consumers of the subsystem - not among the components of the subsystem.



回答7:

You can find details about Facade pattern in this SE question:

What is Facade Design Pattern?

Facade provides a simple and unified interface to complex system.

Real world example (cleartrip flight+hotel booking) is available in this post:

What is Facade Design Pattern?

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.

A real world example of Mesh network topology has been provided in below SE question:

Mediator Vs Observer Object-Oriented Design Patterns

Regarding your query on Mediator adds responsibility:

  1. Facade provides only interface to existing sub-systems. Existing sub-systems are not aware of Facade class itself.

  2. Mediator knows about colleague objects. It enables communication between different colleagues. In the example I have quoted in linked question, ConcreteMediator(NetworkMediator) sends notifications of register and unregister event of one colleague to all other colleagues.



回答8:

Both impose some kind of policy on another group of objects. Facade imposes the policy from above, and Mediator imposes the policy from below. The use of Facade is visible and constraining, while the use of Mediator is invisible and enabling.

The Facade pattern is used when you want to provide a simple and specific interface to a group of objects that has a complex and general interface.

The Mediator pattern also imposes policy. However, whereas Facade imposed its policy in a visible and constraining way, Mediator imposes its policies in a hidden and unconstrained way.

Agile Software Development, Principles, Patterns, and Practices Robert C. Martin.