新旧两个接口,功能类似,旧的接口已渐渐不再使用,如何让旧接口调整为新接口的样式呢(方便其他程序调用)?写一个衔接作用的adapter即可。
如下:Duck和Turkey是两个接口,他们的功能类似,仅仅是方法的名称不同。如何把Turkey接口调整成Duck,以方便调用呢?
package javaapplication31;
public class Main {
public static void main(String[] args) {
Duck duck = new MallardDuck();
duck.quack();
Turkey turkey = new WildTurkey();
turkey.gobble();
}
}
interface Duck {
public void quack();
public void fly();
}
class MallardDuck implements Duck {
public void quack() {
System.out.println("Mallard quacked");
}
public void fly() {
System.out.println("Mallard flying");
}
}
interface Turkey {
public void gobble();
public void fly();
}
class WildTurkey implements Turkey {
public void gobble() {
System.out.println("Wild gobbled");
}
public void fly() {
System.out.println("Wild flying");
}
}
新增一个TurkeyAdapter类来完成转换:
package javaapplication31;
public class Main {
public static void main(String[] args) {
Duck duck = new MallardDuck();
duck.quack();
Turkey turkey = new WildTurkey();
duck = new TurkeyAdapter(turkey);
duck.quack();
}
}
interface Duck {
public void quack();
public void fly();
}
class MallardDuck implements Duck {
public void quack() {
System.out.println("Mallard quacked");
}
public void fly() {
System.out.println("Mallard flying");
}
}
class TurkeyAdapter implements Duck {
Turkey turkey;
TurkeyAdapter(Turkey turkey) {
this.turkey = turkey;
}
public void quack() {
turkey.gobble();
}
public void fly() {
turkey.fly();
}
}
interface Turkey {
public void gobble();
public void fly();
}
class WildTurkey implements Turkey {
public void gobble() {
System.out.println("Wild gobbled");
}
public void fly() {
System.out.println("Wild flying");
}
}
看到这个Adapter,是否想到了Command Pattern中的“装载器”呢?异曲同工之妙。