适配器模式

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

适配器模式_第1张图片
Structure

实例Demo

  1. 类图
适配器模式_第2张图片
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. 设计模式

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