美文网首页
适配器模式

适配器模式

作者: keith666 | 来源:发表于2016-05-20 17:52 被阅读9次

    Intent

    • Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
    • Wrap an existing class with a new interface.
    • Impedance match an old component to a new system

    Structure

    Adapter by keith
    1. 代码:
    public class Adapter {
        public static void main(String[] args) {
            Dog dog = new Dog();
            Flyable flyable = new FlyAdapter(dog);
            flyable.fly();
        }
    }
    //dog can't fly
    class Dog {
        void running() {
            System.out.print("Dog is running");
        }
    }
    interface Flyable {
        void fly();
    }
    // adapter convert dog to be a flyable object
    class FlyAdapter implements Flyable {
        Dog dog;
    
        public FlyAdapter(Dog dog) {
            this.dog = dog;
        }
    
        @Override
        public void fly() {
            dog.running();
        }
    }
    
    1. Output
    Dog is running
    

    Refenrence

    1. Design Patterns
    2. 设计模式

    相关文章

      网友评论

          本文标题:适配器模式

          本文链接:https://www.haomeiwen.com/subject/wvpnrttx.html