Convert the interface of a class into another interface that clients expect. The adapter pattern lets classes work together that couldn’t otherwise because of incompatible interfaces.
鸭子接口及实现
/**
* 鸭子
*/
public interface IDuck {
void quack();
void fly();
}
public class MallardDuck implements IDuck {
@Override
public void quack() {
System.out.println("Quack...");
}
@Override
public void fly() {
System.out.println("Fly...");
}
}
火鸡接口及实现
/**
* 火鸡
*/
public interface ITurkey {
void gobble();
void fly();
}
public class WildTurkey implements ITurkey {
@Override
public void gobble() {
System.out.println("Gobble...");
}
@Override
public void fly() {
System.out.println("Short fly...");
}
}
适配器
火鸡不能直接当作鸭子来用,需要添加适配器,将火鸡可以被当做鸭子来用。
/**
* 现在缺少 Duck ,需要使用 Turkey 来代替Duck。
* 将Turkey适配为Duck,需要实现Duck接口(is a duck),并集成Turkey(has a turkey)
*/
public class TurkeyAdapter implements IDuck {
ITurkey turkey;
public TurkeyAdapter(ITurkey turkey) {
this.turkey = turkey;
}
@Override
public void quack() {
turkey.gobble();
}
@Override
public void fly() {
// Turkey要飞五次才抵上Duck飞一次
for (int i = 0; i < 5; i++) {
turkey.fly();
}
}
}
执行
public class Test {
public static void main(String[] args) {
IDuck mallardDuck = new MallardDuck();
ITurkey wildTurkey = new WildTurkey();
IDuck turkeyAdapter = new TurkeyAdapter(wildTurkey);
System.out.println("Turkey:");
wildTurkey.gobble();
wildTurkey.fly();
System.out.println("Duck:");
testDuck(mallardDuck);
System.out.println("TurkeyAdapter:");
testDuck(turkeyAdapter);
}
static void testDuck(IDuck duck) {
duck.quack();
duck.fly();
}
}
类图
Adapter vs Proxy
- Adapter实现一个接口,使用另外一个接口;而Proxy实现同一个接口;
- Adapter更强调Convert转换,需要做额外的工作来使用另一个接口;代理是另一个对象的占位符,Proxy更强调 延迟初始化,访问控制等。
参考: