# 设计模式 第六章 适配器模式
前言
适配器模式,结构型模式,将某个类的接口转换成另一个接口
表示,主要目的是兼容性,让原本因接口不匹配不能一起工作
的二个类可以协同工作,别名包装器。
适配器模式三种方法:
1. 类适配器
2. 对象适配器
3. 接口适配器
一、类适配器
1.介绍
适配器类通过继承src类,实现dst类的接口,
完成src->dst的适配。
2.代码示例
public class Animal{
void eat();
}
public interface Voltage{
void eatAll();
}
public class VoltageAdapter extends Animal implements Voltage{
@Override
public void eatAll() {
eat();
System.out.println("适配器吃");
}
}
public class Dog{
public void eat(Voltage voltage) {
voltage.eatAll();
}
}
二、对象适配器
1.介绍
同类适配器,将Adapter类不在继承src类,而是特有src类的
实例,以解决兼容性的问题。持有src类实现dst类的接口,
完成src->dst。常用的一种。
2.代码示例
public class Animal{
void eat(){
System.out.println("动物吃");
}
}
public interface Voltage{
void eatAll();
}
public class VoltageAdapter implements Voltage{
private Animal animal;
public VoltageAdapter(Animal animal){
this.animal = animal;
}
@Override
public void eatAll() {
animal.eat();
System.out.println("适配器吃");
}
}
public class Dog{
public void eat(Voltage voltage) {
voltage.eatAll();
}
}
三、接口适配器模式
1.介绍
又称缺省适配器模式,当不需要全部实现接口的方法时,
设计一个抽象类实现接口,并为该接口中每个方法提供一个
默认实现,那么该抽象的子类可有选择的覆盖父类的某些方法。
2.代码示例
public class Animal{
void eat(){
System.out.println("动物吃");
}
}
public interface InterfaceM{
void m1();
void m2();
void m3();
void 4();
}
public abstract class VoltageAdapter implements InterfaceM{
void m1(){
}
void m2(){
}
void m3(){
}
void 4(){
}
}
public class Dog{
public static void main(String[] args) {
VoltageAdapter voltageAdapter = new VoltageAdapter(){
@Override
void m1(){
System.out.println("m1方法");
}
}
}
}