一.前言
适配器,我们应该很常见才对,以前美版或者欧版的iphone充电时,需要一个充电器的转接头,那个转换头就是适配器。一句话适配器:使这样东西看起来像那样东西,就是适配器模式
二.很简单很简单的例子
一个很荒唐的需求,怎么让一只鸭子看起来像一只火鸡。
鸭子的接口以及绿头鸭类:
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");
}
}
火鸡的接口以及野生火鸡类:
public interface Turkey {
public void gobble();
public void fly();
}
public class WildTurkey implements Turkey {
//咯咯叫
public void gobble() {
System.out.println("Gobble gobble");
}
public void fly() {
System.out.println("I'm flying a short distance");
}
}
让火鸡看起来像一只鸭子,这时候就需要适配器,经过适配器后使火鸡看起来像一只鸭子:
public class TurkeyAdapter implements Duck {
Turkey turkey;
public TurkeyAdapter(Turkey turkey) {
this.turkey = turkey;
}
public void quack() {
turkey.gobble();
}
public void fly() {
for(int i=0; i < 5; i++) {
turkey.fly();
}
}
}
下面是测试函数:
public class DuckTestDrive {
public static void main(String[] args) {
MallardDuck duck = new MallardDuck();
WildTurkey turkey = new WildTurkey();
Duck turkeyAdapter = new TurkeyAdapter(turkey);
System.out.println("The Turkey says...");
turkey.gobble();
turkey.fly();
System.out.println("\nThe Duck says...");
testDuck(duck);
System.out.println("\nThe TurkeyAdapter says...");
testDuck(turkeyAdapter);
}
static void testDuck(Duck duck) {
duck.quack();
duck.fly();
}
}
三.真实世界的适配器
在java的集合中,如Stach,Hashtable,Vector的elements()方法都会返回一个Enumeration,而它和Iterator又很像在java中,迭代器和枚举类很像,怎样实现他们之间的适配,先看如下图:
适配器EnumerationIterator,从枚举到迭代:
public class EnumerationIterator implements Iterator {
Enumeration enumeration;
public EnumerationIterator(Enumeration enumeration) {
this.enumeration = enumeration;
}
public boolean hasNext() {
return enumeration.hasMoreElements();
}
public Object next() {
return enumeration.nextElement();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
测试函数:
public class IteratorEnumerationTestDrive {
public static void main (String args[]) {
ArrayList l = new ArrayList(Arrays.asList(args));
Enumeration enumeration = new IteratorEnumeration(l.iterator());
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
}
以上