模式思想
改变一个类的对外接口(增加或减少),以满足不同外部调用者的需求;
角色成员
目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
需要适配的类(Adaptee):需要适配的类或适配者类。
适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。
3种实现形式
适配的接口
public interface ITarget {
public void internet();
public void bluetooth();
}
- -缺省适配器- -
Adpater负责适配的接口的所有默认实现,其他需要适配的类只要继承自它,则完成适配;
Adapter
public class Adapter implements ITarget{
//缺省适配器,和其他两种稍有不同
@Override
public void internet() {
// TODO Auto-generated method stub
//Empty Method
}
@Override
public void bluetooth() {
// TODO Auto-generated method stub
//Empty Method
}
}
Adaptee
public class Adaptee extends Adapter {
public void internet(){
System.out.println("I can surf the internet... ::"+Adaptee.class);
}
}
- - 类适配器- -
适配器(Adapter)继承某一个需要的类(Adaptee),保留它原来的方法,同时实现适配的接口(ITarget),添加Adaptee中缺少的方法
Adapter
public class Adapter extends Adaptee implements ITarget{
//类适配器
@Override
public void bluetooth() {
// TODO Auto-generated method stub
System.out.println("I can use the bluetooth...::"+Adapter.class);
}
}
Adaptee
public class Adaptee {
public void internet(){
System.out.println("I can surf the internet... ::"+Adaptee.class);
}
public void phoneCall(){
System.out.println("I can make a phone call...::"+Adaptee.class);
}
}
- - 对象适配器- -
适配器(Adapter)包含需要适配的类(Adaptee)的一个实例对象,在Adaptee能够实现的功能,由这个实例对象完成,缺少的方法由Adapter实现;
Adapter
public class Adapter implements ITarget{
//对象适配器
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
@Override
public void internet() {
// TODO Auto-generated method stub
this.adaptee.internet();
}
@Override
public void bluetooth() {
// TODO Auto-generated method stub
System.out.println("I can use the bluetooth...");
}
}
Adaptee
public class Adaptee {
public void internet(){
System.out.println("I can surf the internet... ::"+Adaptee.class);
}
public void phoneCall(){
System.out.println("I can make a phone call...::"+Adaptee.class);
}
}