Java 基础
Java 容器
Java 并发
设计模式
目录

适配器

# 1. 适配器(Adapter)

# Intent

把一个类接口转换成另一个用户需要的接口。


# Class Diagram


# Implementation

鸭子(Duck)和火鸡(Turkey)拥有不同的叫声,Duck 的叫声调用 quack() 方法,而 Turkey 调用 gobble() 方法。

要求将 Turkey 的 gobble() 方法适配成 Duck 的 quack() 方法,从而让火鸡冒充鸭子!

package com.code.structural.example2;

public interface Duck {
    void quack();
}
1
2
3
4
5
package com.code.structural.example2;

public interface Turkey {
    void gobble();
}
1
2
3
4
5
package com.code.structural.example2;

public class WildTurkey implements Turkey {
    @Override
    public void gobble() {
        System.out.println("gobble!");
    }
}
1
2
3
4
5
6
7
8
package com.code.structural.example2;

public class TurkeyAdapter implements Duck {
    Turkey turkey;

    public TurkeyAdapter(Turkey turkey) {
        this.turkey = turkey;
    }

    @Override
    public void quack() {
        turkey.gobble();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.code.structural.example2;

public class Main {
    public static void main(String[] args) {
        Turkey turkey = new WildTurkey();
        Duck duck = new TurkeyAdapter(turkey);
        duck.quack();
    }
}
1
2
3
4
5
6
7
8
9

# JDK

  • java.util.Arrays#asList() (opens new window)
  • java.util.Collections#list() (opens new window)
  • java.util.Collections#enumeration() (opens new window)
  • javax.xml.bind.annotation.adapters.XMLAdapter (opens new window)