Search code examples
javadesign-patternsfacademediator

Difference between Facade and Mediator Design pattern?


What is the difference between facade and mediator design pattern. I want understand which design pattern to choose between these two in which scenario. I was going through the following links and found both same in terms of use case.

Facade design pattern : http://www.tutorialspoint.com/design_pattern/facade_pattern.htm

Mediator design pattern : http://www.java2s.com/Tutorial/Java/0460__Design-Pattern/CoordinatingYourObjectswiththeMediatorPatterns.htm

I have confusion in following code segment which looks similar in both the design patterns.

Facade class:

public class ShapeMaker {
   private Shape circle;
   private Shape rectangle;
   private Shape square;

   public ShapeMaker() {
      circle = new Circle();
      rectangle = new Rectangle();
      square = new Square();
   }

   public void drawCircle(){
     circle.draw();
   }
   public void drawRectangle(){
     rectangle.draw();
   }
   public void drawSquare(){
     square.draw();
   }
}

Mediator class :

   public class Mediator {
         Welcome welcome;
         Browse browse;
         Purchase purchase;
         Exit exit;

        public Mediator() {
          welcome = new Welcome(this);
          browse = new Browse(this);
          purchase = new Purchase(this);
          exit = new Exit(this);
       }

      public void handle(String state) {
          if (state.equals("welcome.shop")) {
            browse.execute();
      } else if (state.equals("shop.purchase")) {
            purchase.execute();
      } else if (state.equals("purchase.exit")) {
             exit.execute();
      }

Solution

  • I have confusion in following code segment which looks similar in both the design patterns.

    I think you're seeing the composition aspects of both patterns.

    Facade links to various existing classes of a subsystem to add some typical functionality that simplifies use of the subsystem. In the example code you cited, ShapeMaker provides services that facilitate making shapes.

    Mediator links to various colleagues that have to collaborate, so as to minimize the knowledge the colleagues have about each other. Minimizing knowledge has the side effect of reducing coupling between colleagues (they only know the mediator) and increasing their cohesion (they generally have less to worry about since they don't know about the bigger picture).

    In both patterns, the centralized class assumes responsibility for the complexity of dealing with the classes it is linked to.

    Here are the basic patterns in UML from the Gang of Four:

    Facade pattern

    Mediator pattern