适配器模式

适配器模式将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。

示例—鸭子与火鸡

鸭子与火鸡是两个品种,但现在假设你缺鸭子对象,想用一些火鸡对象来冒充。显而易见,因为火鸡的接口不同,所以我们不能公然拿来用。

UML图表示

适配器模式-鸭子与火鸡

代码演示

鸭子接口

package Adapter;

public interface Duck {
    void quack();
    void fly();
}

火鸡接口

package Adapter;

public interface Turkey {
    void gobble();
    void fly();
}

绿头鸭

package Adapter;

public class MallardDuck implements Duck {
    @Override
    public void quack() {
        System.out.println("Quack");
    }

    @Override
    public void fly() {
        System.out.println("I'm flying");
    }
}

野火鸡

package Adapter;

public class WildTurkey implements Turkey {
    @Override
    public void gobble() {
        System.out.println("Gobble gobble");
    }

    @Override
    public void fly() {
        System.out.println("I'm flying short distance");
    }
}

火鸡适配鸭子的类

package Adapter;

public class TurkeyAdapter implements Duck {

    Turkey turkey;

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

    @Override
    public void quack() {
        turkey.gobble();
    }

    @Override
    public void fly() {
        for (int i = 0; i < 5; i++)
        turkey.fly();
    }
}

测试调用代码

package Adapter;

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();
    }
}

测试结果

The Turkey says...
Gobble gobble
I'm flying short distance

The Duck says...
Quack
I'm flying

The TurkeyAdapter says...
Gobble gobble
I'm flying short distance
I'm flying short distance
I'm flying short distance
I'm flying short distance
I'm flying short distance

你可能感兴趣的:(适配器模式)