Search code examples
oopdesign-patternsadapterobject-oriented-analysismediator

What is the exact difference between 'Adapter' and 'Mediator" patterns?


I know that Adapter is a structural pattern and Mediator is a behavioral one. But as far I understood, what both of them are doing, is connecting two (or more) other classes which are potentially incompatible (not so maintainable) for direct communication.

Can some one give a close comparison between these two and point out the exact difference?

These are the links for Adapter and Mediator explanations in TutorialsPoint.

And these are sourcemaking explanations. Adapter, Mediator.


Solution

  • They don't have much in common, IMO.

    A mediator is used to avoid coupling several components together. Instead of each component "talking" with each other directly (and thus having to know each other and to know how to communicate all with each other), each component talks to a single object: the mediator. The name is chosen on purpose: when you're fighting with your neighbor and can't communicate with him, you go see a mediator and instead of talking to each other, you both talk with the mediator, who tries fixing the issue.

    An adapter is used to "transform" an object with an interface into an object with an other interface. Just like, for example, an electrical adapter which transforms a european power outlet into an american one, so that you can use your American shaver in Europe. Simple example: you need to store a Runnable into a list of Callables. Runnable has a method run(). Callable has a method call(). You thus create an Adapter:

    public class RunnableAdapter implements Callable {
        private Runnable runnable;
    
        public RunnableAdapter(Runnable runnable) {
            this.runnable = runnable;
        }
    
        public void call() {
            runnable.run();
        }
    }