概要

  • 设计模式是结构型模式
  • 让原来不兼容的两个接口协同工作

    类适配器

  1. interface Player {
  2. void action();
  3. }
  4. interface Mp4 {
  5. void play();
  6. }
  7. class ExpensiveMp4 implements Mp4 {
  8. @Override
  9. public void play() {
  10. System.out.println("play mp4");
  11. }
  12. }
  13. public class PlayerAdapter extends ExpensiveMp4 implements Player {
  14. @Override
  15. public void action() {
  16. play();
  17. }
  18. }

接口适配器

  1. interface Player {
  2. void action();
  3. }
  4. interface Mp4 {
  5. void play();
  6. }
  7. class ExpensiveMp4 implements Mp4 {
  8. @Override
  9. public void play() {
  10. System.out.println("play mp4");
  11. }
  12. }
  13. public class PlayerAdapter implements Player {
  14. private Mp4 mp4;
  15. public PlayerAdapter(Mp4 mp4) {
  16. this.mp4 = mp4;
  17. }
  18. @Override
  19. public void action() {
  20. mp4.play();
  21. }
  22. }

总结

  • 提高代码复用
  • 灵活性非常好
  • 适配器其实是对目标类/接口的包装,实际工作只有目标类/接口