1.适配器模式(Adapter Pattern):将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作。
2.实现软件复用和接口转换
(1)Target(目标抽象类):定义了特定的工作接口。
(2)Adapter(适配器类):模式的核心类,作为转换器对Target和Adaptee进行适配。
(3)Adaptee(适配者类):定义了需要适配的接口。
对象匹配:
package 适配器模式;
public class AdapterPattern {
public static void main(String[] args) {
new Adapter(new Adaptee()).Adaptee();
}
}
class Adaptee{
public void Adaptee(){
System.out.println("11111");
}
}
class Adapter{
private Adaptee at;
public Adapter(Adaptee t){
at = t;
}
public void Adaptee(){
at.Adaptee();
}
}
接口/类适配:
package 适配器模式;
public class ClassAdapterPattern {
public static void main(String[] args) {
Target tt = new AdapterA(new Adaptee2(3));
tt.Print();
}
}
interface Target{
void Print();
}
class AdapterA implements Target{
private Adaptee2 pc = null;
public AdapterA(Adaptee2 c){
pc = c;
}
public void Print() {
pc.Print(pc.getC());
}
}
class AdapterB implements Target{
private Adaptee2 pc = null;
public AdapterB(Adaptee2 c){
pc = c;
}
public void Print() {
pc.Print();
}
}
class Adaptee2{
private int c;
public Adaptee2(int ttt){
c = ttt;
}
public void Print(int t){
System.out.println(t);
}
public void Print(){
System.out.println(0);
}
public int getC() {
return c;
}
}
优点
耦合性低。将目标类和适配者类解耦,通过引入一个适配器类来重用现有的适配者类,而无须修改原有代码。
增加了类的透明性和复用性。将具体的实现封装在适配者类中,对于客户端类来说是透明的,而且提高了适配者的复用性。
符合“开闭原则”。可以在不修改原有代码的基础上增加新的适配器类。
对象适配器还具有以下优点
一个适配器可以匹配多个适配者。
类适配器还具有以下优点
灵活性更强。因为适配器类是适配者类的子类,所以在适配器类中可以覆盖适配者类中的方法。
类适配器缺点
适配器类只能适配一个适配者。
对象适配器缺点
灵活性不强。在适配器类中覆盖适配者类中的方法较为困难。