loading...
Cover image for Design Pattern: The Adapter & Facade Patterns

Design Pattern: The Adapter & Facade Patterns

danlee0528 profile image Daniel Lee ・2 min read

The Adapter Pattern

The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because incompatible interfaces.

Diagram example.

  1. The client makes a request to the adapter by calling a method on it using the target interface
  2. The adapter translates the request into one or more calls on the adaptee using the adaptee interface
  3. The client receives the results of the call and never knows there is an adapter doing the translation

There're two types of adapters: object and class

  1. Object adapters use composition to adapt the adaptee
  2. Class adapters use inheritance to adapt the adaptee
    • In Java, multiple inheritance can't implement it

More concrete example with code.

Client

public interface Duck{
    public void quack();
    public void fly();
}

public class MallardDuck implements Duck{
    public void quack(){
        system.out.println("Quack");
    }
    
    public void fly(){
        system.out.println("I'm flying");
    }
}

Adaptee

public interface Turkey{
    public void gobble();
    public void fly();
}

public class WildTurkey impelements Turkey{
    public void gobble(){
        system.out.println("Gobble Gobble");
    }

    public void fly(){
        system.out.println("I'm flying a short distance");
    }
}

Adapter

public Turkey Adapter implements Duck{
    Turkey turkey;
   
    public TurkeyAdapter(Turkey turkey){
        this.turkey = turkey; // get a reference to the object that we're adapting
    }

    public void quack(){
        turkey.gobble();
    }

    public void fly(){
        turkey.fly();
    }
}

The Facade Pattern

The Facade Pattern provides a unified interface to a set of interfaces into a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use

It takes a complex subsystem and make it easier to use by implementing a Facade class that provides one more reasonable interface. (simplified and unified)

A facade not only simplifies an interface, it also decouples a client from a subsystem of components

Facades and adapters may wrap multiple classes, but a facade's intent is to simplify, while an adapter's is to convert the interface to something different

Posted on by:

danlee0528 profile

Daniel Lee

@danlee0528

I love interactive & visual technology and playing with data.

Discussion

pic
Editor guide