适配器模式的用意是将接口不同而功能相同或者相近的两个接口加以转换。
适配器模式中存在三个角色:一是目标Target,它是目标接口,最近得到的类要具有它的接口形式;二是被适配的源类Adaptee,它的功能与Target所描述的接口有相似的地方,但是它无法成为Target的实现类,所提供的方法不全,或者不完全符合要求;三是适配器类Adapter,它的功能是把Adaptee转化为目标接口Target。
适配器模式分为两种,一是类适配,一是对象适配。
适配器模式中存在三个角色:一是目标Target,它是目标接口,最近得到的类要具有它的接口形式;二是被适配的源类Adaptee,它的功能与Target所描述的接口有相似的地方,但是它无法成为Target的实现类,所提供的方法不全,或者不完全符合要求;三是适配器类Adapter,它的功能是把Adaptee转化为目标接口Target。
适配器模式分为两种,一是类适配,一是对象适配。
package
adapter;
public interface Target ... {
void function1();
void function2();
}
package adapter;
public class Adaptee ... {
public void function1() ...{
System.out.println(this + ".function1()");
}
}
package adapter;
public class ClassAdapter extends Adaptee implements Target ... {
public void function2() ...{
System.out.println(this + ".function2()");
}
}
package adapter;
public class ObjectAdapter implements Target ... {
private Adaptee adaptee;
public ObjectAdapter (Adaptee a) ...{
adaptee = a;
}
public void function1() ...{
adaptee.function1();
}
public void function2() ...{
System.out.println(this + ".function2()");
}
}
package adapter;
public class Operator ... {
public static void main(String[] args) ...{
ClassAdapter classAdapter = new ClassAdapter();
classAdapter.function1();
classAdapter.function2();
ObjectAdapter objectAdapter = new ObjectAdapter(new Adaptee());
objectAdapter.function1();
objectAdapter.function2();
}
}
public interface Target ... {
void function1();
void function2();
}
package adapter;
public class Adaptee ... {
public void function1() ...{
System.out.println(this + ".function1()");
}
}
package adapter;
public class ClassAdapter extends Adaptee implements Target ... {
public void function2() ...{
System.out.println(this + ".function2()");
}
}
package adapter;
public class ObjectAdapter implements Target ... {
private Adaptee adaptee;
public ObjectAdapter (Adaptee a) ...{
adaptee = a;
}
public void function1() ...{
adaptee.function1();
}
public void function2() ...{
System.out.println(this + ".function2()");
}
}
package adapter;
public class Operator ... {
public static void main(String[] args) ...{
ClassAdapter classAdapter = new ClassAdapter();
classAdapter.function1();
classAdapter.function2();
ObjectAdapter objectAdapter = new ObjectAdapter(new Adaptee());
objectAdapter.function1();
objectAdapter.function2();
}
}
结果如下:
adapter.ClassAdapter@765291.function1()
adapter.ClassAdapter@765291.function2()
adapter.Adaptee@14f8dab.function1()
adapter.ObjectAdapter@1ddebc3.function2()