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
- 代码:
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();
}
}
- Output
Dog is running
Refenrence
- Design Patterns
- 设计模式
网友评论