适配器模式

    适配器模式(Adapter Pattern)就是对一个类做适配,使之符合客户端的需求,能够正常的工作。

    就像是变压器(Adapter),美国的生活电压是110V,中国的是220V,美国的电器要在中国使用就需要加上一个变压器(Adapter)。

    适配器模式也被称为包装模式(Wrapper Pattern),将已有的类进行包装,使之具有需求所需的接口。

    适配器模式有以下两种:类的适配器模式和对象的适配器模式。

    

    类的适配器模式的类图关系如下:

    

       Target:目标角色,包含所有期望拥有的接口

       Adaptee:现有的类,需做适配

       Adapter:适配Adaptee符合Target      

public interface Target {   
    void sampleOperation1();
    void sampleOperation2();
}

  

public class Adaptee {
    public void sampleOperation1(){}
}

  

public class Adapter extends Adaptee implements Target {
   
    public void sampleOperation2(){
        // Write your code here
    }
}

  对象的适配器模式的类图关系如下:

 

    对象的适配器模式与类的适配器模式的区别在于: Adapter与Adaptee的关系不是继承,而是关联。 Adapter直接调用Adaptee。

public class Adapter implements Target {
    public Adapter(Adaptee adaptee){
        super();
        this.adaptee = adaptee;
    }

    public void sampleOperation1(){
        adaptee.sampleOperation1();
    }

    public void sampleOperation2(){
        // Write your code here
    }

    private Adaptee adaptee;
}

  下面的情况下可以考虑使用适配器:

       1.系统需要使用现有的类,但是现有类的接口又不符合。

       2.需要创建一个可以重复使用的类,用于一些彼此没有太大关联的类,包括一些可能在将来引进的类。

        

      Enumeration接口较Iterator较早出现在JDK中,2者之间如果不做转换,使用起来是比较麻烦的。可能定义了一个Iterator,但方法的参数是Enumeration。

      下面就是Iterator适配到Enumeration的类图。

      

        

public class Itermeration implements Enumeration{
	private Iterator it;

    public Itermeration(Iterator it)
    {
        this.it = it;
    }

    public boolean hasMoreElements()
    {
        return it.hasNext();
    }

    public Object nextElement() throws NoSuchElementException
    {
		return it.next();
    }
}

  JDBC使得Java语言可以连接到数据库,并使用SQL操作数据。各具体的数据库要适配JDBC使其能够适用于具体的数据库连接。

      使用适配器模式时有一些需要注意的事:

      1.目标接口可以省略,源是一个接口,适配器需要实现源中的方法,可以不必实现不需要的方法,见缺省适配模式。

      2.适配器可以是抽象类,见缺省适配模式。

      3.带参数的适配器模式,适配器可以根据参数返回一个合适的类给客户端。

原文地址:https://www.cnblogs.com/lnlvinso/p/3839826.html