0
点赞
收藏
分享

微信扫一扫

设计模式 之适配器模式

适配器模式

(适配器模式)

定义

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

适配器模式充满着良好的OO设计原则:使用对象组合,以修改的接口包装被适配者。这种做法还有额外的优点,那就是被适配者的任何子类都可以搭配着适配器使用。

角色

  • Target(目标抽象类):把其他类转换为我们期望的接口,可以是一个抽象类或接口,也可以是具体类
  • Adaptee (装饰者):不改变接口,但加入责任
  • Adapter(适配者):将一个接口转成另一个接口

代码实现

现有鸭子和火鸡,需要让火鸡冒充鸭子

  1. 鸭子类

    public interface Duck {
        public void quack();
        public void fly();
    }
    
    public class MallardDuck implements Duck {
        @Override
        public void quack() {
            System.out.println("Quack");
        }
    
        @Override
        public void fly() {
            System.out.println("I'm flying");
        }
    }
    
  2. 火鸡类

    public interface Turkey {
        public void gobble();
        public void fly();
    }
    
    public class WildTurkey implements Turkey {
        @Override
        public void gobble() {
            System.out.println("Gobble gobble");
        }
    
        @Override
        public void fly() {
            System.out.println("I'm flying a short distance");
        }
    }
    
  3. 适配器

    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();
            }
        }
    }
    
  4. 测试代码

    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();
        }
    }
    
  5. 输出结果

    The Turkey says...
    Gobble gobble
    I'm flying a short distance
    
    The Duck says...
    Quack
    I'm flying
    
    The TurkeyAdapter says...
    Gobble gobble
    I'm flying a short distance
    I'm flying a short distance
    I'm flying a short distance
    I'm flying a short distance
    I'm flying a short distance
    
举报

相关推荐

0 条评论