代码演示
鸭子接口:
package com.java.jikexueyuan.adaptermode.duck; public interface Duck { public void quack(); public void fly(); }
绿头鸭实现鸭子接口;
package com.java.jikexueyuan.adaptermode.duck; public class GreenHeadDuck implements Duck { @Override public void quack() { // TODO Auto-generated method stub System.out.println(" Ga Ga"); } @Override public void fly() { // TODO Auto-generated method stub System.out.println("I am flying a long distance"); } }
火鸡接口:
package com.java.jikexueyuan.adaptermode.turkey; public interface Turkey { public void gobble(); public void fly(); }
火鸡实现类:
package com.java.jikexueyuan.adaptermode.turkey; public class WildTurkey implements Turkey { @Override public void gobble() { // TODO Auto-generated method stub System.out.println(" Go Go"); } @Override public void fly() { // TODO Auto-generated method stub System.out.println("I am flying a short distance"); } }
适配器对外展示的是鸭子的形式,所以实现鸭子的接口
package com.java.jikexueyuan.adaptermode.adapter; import com.java.jikexueyuan.adaptermode.duck.Duck; import com.java.jikexueyuan.adaptermode.turkey.Turkey; public class TurkeyAdapter implements Duck { private Turkey turkey; public TurkeyAdapter(Turkey turkey) { this.turkey=turkey; } @Override public void quack() { // TODO Auto-generated method stub turkey.gobble(); } @Override public void fly() { // TODO Auto-generated method stub for(int i=0;i<6;i++) { turkey.fly(); //模拟鸭子飞的远 } } }
适配器模式:将一个类的接口转换成另一种接口.让原本接口不兼容的类可以兼容
从用户的角度看不到被适配者,是解耦的
用户调用适配器转化出来的目标接口方法
适配器再调用被适配者的相关接口方法
用户收到反馈结果,感觉只是和目标接口交互
对象适配器与类适配器
类适配器:通过多重继承目标接口和被适配者类方式来实现适配
多重继承,其中继承的目标接口部分达到适配目的,而继承被适配者类的部分达到通过调用被适配者类里的方法来实现目标接口的功能
对象适配器与类适配器差异
对象适配器和类适配器使用了不同的方法实现适配,对象适配器使用组合,类适配器使用继承.
使用类适配器重新实现上边的例子:
适配器:
package com.java.jikexueyuan.adaptermode.adapter; import com.java.jikexueyuan.adaptermode.duck.Duck; import com.java.jikexueyuan.adaptermode.turkey.WildTurkey; public class TurkeyAdapter2 extends WildTurkey implements Duck { @Override public void quack() { // TODO Auto-generated method stub super.gobble(); } @Override public void fly() { // TODO Auto-generated method stub super.fly(); super.fly(); super.fly(); } }
实例:从枚举器到迭代器的适配
package com.java.jikexueyuan.adaptermode.adapter; import java.util.Enumeration; import java.util.Iterator; public class EnumerationIterator implements Iterator<Object> { private Enumeration enumeration; public EnumerationIterator(Enumeration enumeration) { this.enumeration= enumeration; } @Override public boolean hasNext() { // TODO Auto-generated method stub return enumeration.hasMoreElements(); } @Override public Object next() { // TODO Auto-generated method stub return enumeration.nextElement(); } @Override public void remove() { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } }