------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
适配器设计模式:将不同接口的类转换成一个理想的接口,使该接口能兼容之前不同接口的类。
适用场合:1.系统需要使用已经存在的类,但是系统的接口与存在的类的接口不兼容,且不允许修改已经存在的类
2. 想要建立一个新类,为了使其和其他没多大关系的类或者以后可能将要引进的类一起工作。
适配器模式一般有两种方法,一种是类适配器,还有一种是方法适配器。请看下例:
目标接口(Target):客户希望的接口,标准接口。
需要适配的类(Adaptee):需要被适配的类。
适配器(Adapter):将原接口转换成标准接口的类。
类适配器:
//已存在的,具有特殊功能,但不符合我们已有的标准接口的类;
class Adaptee {
public void specificRequest(){
System.out.println("specificRequest class");
}
}
//目标接口,标准接口,用户希望的接口,能适合特殊功能的接口;
interface Target {
public void request();
}
//原有类,只有普通功能
class ConcreteTarget implements Target {
public void request (){
System.out.println("common class");
}
}
//适配器类,继承了被适配的类,同时实现标准接口;
class Adapter extends Adaptee implements Target {
public void request() {
super.specificRequest();
}
}
public class testTarget {
public static void main(String[] args) {
Target concreteTarget = new ConcreteTarget();
concreteTarget.request();
Target adapter = new Adapter();
adapter.request();
}
}/*Output:
common class
specificRequest class
*/
------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
class Adapter implements Target {
private Adaptee adaptee;
public Adapter( Adaptee adaptee){
this.adaptee = adaptee;
}
public void request() {
this.adaptee.specificRequest();
}
}
public class testTarget {
public static void main(String[] args) {
Target concreteTarget = new ConcreteTarget();
concreteTarget.request();
Target adapter = new Adapter();
adapter.request();
}
}/*Output:
common class
specificRequest class
*/