aka:Wrapper (包装器)
鸭子与火鸡:
If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a duck adapter
如果它像鸭子一样走路,那么它可能是一只带着鸭子适配器的火鸡
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();}
}
public class DuckAdapter implements Turkey {Duck duck;Random rand;public DuckAdapter(Duck duck) {this.duck = duck;rand = new Random();}public void gobble() {duck.quack();}public void fly() {if (rand.nextInt(5) == 0) {duck.fly();}}
}
public class TurkeyTestDrive {public static void main(String[] args) {MallardDuck duck = new MallardDuck();Turkey duckAdapter = new DuckAdapter(duck);for (int i = 0; i < 10; i++) {System.out.println("The DuckAdapter says...");duckAdapter.gobble();duckAdapter.fly();}}
}
The early collections types (Vector, Stack, Hashtable, and a few others) implement a method elements(), which returns an Enumeration.
Adapting an Enumeration to an Iterator.
@SuppressWarnings("unchecked")
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 EnumerationIteratorTestDrive {@SuppressWarnings("unchecked")public static void main (String args[]) {// Vector v = new Vector(Arrays.asList(args));Vector v = new Vector(Arrays.asList("A", "B", "C", "E", "F", "G"));Iterator iterator = new EnumerationIterator(v.elements());while (iterator.hasNext()) {System.out.println(iterator.next());}}
}
以迭代器形式遍历枚举。