Design pattern adapter pattern

Posted by Naug on Tue, 19 Nov 2019 20:23:30 +0100

github project: https://github.com/wangjianxiandev/design

  • Turkey posing as duck:
    Suppose that the duck is made by one company, but another company makes a turkey. But if the turkey wants to be a duck, it needs to introduce an adapter between the turkey and the duck. After the adapter, the outside world looks like a duck, so the turkey inherits a duck, but the calling content is the turkey content.
  • First, declare the interface between duck and Turkey
package shipeiqi;
public interface Duck {
    public void gaga();
    public void fly();
}



public interface Turkey {
    public void gogo();
    public void fly();
}
  • Implementation interface
public class RedDuck implements Duck {


    @Override
    public void gaga() {
        System.out.println("Ga Ga");
    }


    @Override
    public void fly() {
        System.out.println("Fly a long distance");
    }
}


public class RedTurkey implements Turkey {
    @Override
    public void gogo() {
        System.out.println("Go Go");
    }


    @Override
    public void fly() {
        System.out.println("Fly  a short distance");
    }
}
  • Implementation adapter
//The user sees a duck, but in a duck's corresponding way it calls Turkey, which calls like a turkey and flies like a duck.
public class TurkeyAdapter implements Duck {
    private Turkey turkey;
    public TurkeyAdapter(Turkey turkey){
        this.turkey = turkey;
    }
    @Override
    public void gaga() {
        turkey.gogo();
    }


    @Override
    public void fly() {
        for(int i = 0;i<3;i++){
            turkey.fly();//Because ducks fly far away, part of the change
        }
    }
}
  • test
public class MainTest {
    public static void main(String[] args) {
        RedDuck redDuck = new RedDuck();
        RedTurkey redTurkey = new RedTurkey();
        Duck duckTurkey = new TurkeyAdapter(redTurkey);
        duckTurkey.gaga();
        duckTurkey.fly();
    }
}
  • Convert the interface of one class, Turkey class to another duck interface to make the original incompatible interface compatible
    -User calls the target interface method transformed by adapter
    -Adapter calls related interface methods of adapter
    -The user receives the feedback result and feels only interacts with the target interface

Topics: github