适配器模式,把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法再一起工作的两个类能够在一起工作。
适配器模式分两种:对象适配器模式和类适配器模式
对象适配器模式——组合实现。
类适配器模式——集成实现。
现在,现在有一只老虎,它会奔跑这不用说,现在我们要让它“如虎添翼”,让它会飞!
代码实现:
动物基类:
package com.demo.adapter.animal;
public class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Animal() {
}
}
奔跑者接口:
package com.demo.adapter.animal;
public interface IRunner {
public void run();
}
老虎类:
package com.demo.adapter.animal;
public class Tiger extends Animal implements IRunner {
public Tiger() {
setName("Tiger");
}
@Override
public void run() {
System.out.println(getName() + " is able to run.");
}
}
飞行者接口:
package com.demo.adapter.animal;
public interface IFlyer {
public void fly();
}
对象适配器模式实现:
package com.demo.adapter.objectadapter;
import com.demo.adapter.animal.Animal;
import com.demo.adapter.animal.IFlyer;
public class FlyerAdapter implements IFlyer {
/*
** 待转换的对象
*/
private final Animal animal;
/*
** 在构造方法中传人待转换的对象
*/
public FlyerAdapter(Animal animal) {
this.animal = animal;
}
/*
** 实现转换
*/
@Override
public void fly() {
System.out.println(animal.getName() + " is able to fly.");
}
}
测试代码:
package com.demo.adapter.objectadapter;
import com.demo.adapter.animal.Tiger;
public class MainApp {
public static void main(String[] args) {
Tiger tiger = new Tiger();
tiger.run();
FlyerAdapter flyingTiger = new FlyerAdapter(tiger);
flyingTiger.fly();
}
}
结果输出:
Tiger is able to run.
Tiger is able to fly.
类适配器模式实现:
package com.demo.adapter.classadapter;
import com.demo.adapter.animal.Animal;
import com.demo.adapter.animal.IFlyer;
/*
** 继承待转换的类
*/
public class FlyerAdapter extends Animal implements IFlyer {
/*
** 在构造方法中传人待转换的对象
*/
public FlyerAdapter(Animal animal) {
setName(animal.getName());
}
/*
** 实现转换
*/
@Override
public void fly() {
System.out.println(getName() + " is able to fly.");
}
}
测试代码:
package com.demo.adapter.classadapter;
import com.demo.adapter.animal.Tiger;
public class MainApp {
public static void main(String[] args) {
Tiger tiger = new Tiger();
tiger.run();
FlyerAdapter flyingTiger = new FlyerAdapter(tiger);
flyingTiger.fly();
}
}
结果输出:
Tiger is able to run.
Tiger is able to fly.
使用适配器模式的适用场合:
1) 软件系统结构需要升级或扩展,又不想影响原有系统的稳定运行的时候;
2) 转换类之间差别不是太大的时候;
3) 想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类协同工作的时候。
适配器设计模式一般用于系统的升级扩展,或者是版本的兼容性上,一般在软件的设计阶段不会使用适配器模式。在原有类和新的接口标准不应该差别太大,否则,适配器很难达到预期的效果。适配器模式在软件的后期维护具有很大的优势,它不仅能保持原有系统的稳定,而且还能进行新功能的扩展。