简介
适配器模式将某个类的接口(重点是接口)转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。主要分为三类:
-
类的适配器模式
对类做适配;
继承类C并实现接口I;
-
对象的适配器模式
对类的实例化对象做适配;
实现I并持有C的实例化对象;
-
接口的适配器模式。
对接口做适配;
使用抽象类实现接口;
类的适配器模式
需求
目标接口是Animal,但同时想使用Source类;
方法
创建新类继承类实现接口;
适用
希望将一个类转换成满足另一个新接口的类时;
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Source { public void name(){ Test.printMsg("Source.name"); } }
interface Animal { public void name(); public void say(); }
class Dog extends Source implements Animal { @Override public void say(){ Test.printMsg("Dog"); } }
public class Test { public static void printMsg(String msg){ System.out.println(msg); } public static void main(String[] args){ Animal dog = new Dog(); dog.name(); dog.say(); } }
|
对象的适配器模式
需求
同类的适配器
方法
实现接口但持有类的实例化对象;
适用
希望将一个对象转换成满足另一个新接口的对象;
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Source { public void name(){ Test.printMsg("Source.name"); } }
interface Animal { public void name(); public void say(); }
class Dog implements Animal { private Source source; public Dog(Source source){ super(); this.source = source; } @Override public void name(){ Test.printMsg("Dog.name"); } @Override public void say(){ Test.printMsg("Dog.say"); } }
public class Test { public static void printMsg(String msg){ System.out.println(msg); } public static void main(String[] args){ Source source = new Source(); Animal dog = new Dog(source); dog.name(); dog.say(); } }
|
接口的适配器模式
需求
一个接口中有多个抽象方法,但只需要某一个方法(即不需要实现所有抽象方法,这样比较浪费,因为并不是所有方法都需要);
方法
创建抽象类实现接口(实现所有方法),使用时继承抽象类,重写特定方法;
适用
不希望实现一个接口中所有的方法时;
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| interface Source { public void name(); public void say(); }
abstract class Animal implements Source { public void name(){}; public void say(){}; } abstract class Person implements Source { public void name(){}; public void say(){}; }
class Dog extends Animal { public void name(){ Test.printMsg("Dog.name"); } public void say(){ Test.printMsg("Dog.say"); } } class Teacher extends Person { public void name(){ Test.printMsg("Teacher.name"); } public void say(){ Test.printMsg("Teacher.say"); } }
public class Test { public static void printMsg(String msg){ System.out.println(msg); } public static void main(String[] args){ Source dog = new Dog(); dog.name(); dog.say(); Source teacher = new Teacher(); teacher.name(); teacher.say(); } }
|