结构型之适配器模式

来源:互联网 发布:centos 没有桌面 编辑:程序博客网 时间:2024/05/24 03:59

1、适配器模式:将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)
这里写图片描述

2、结构分工    在对象适配器模式结构图中包含如下几个角色:        Target(目标抽象类):目标抽象类定义客户所需接口,可以是一个抽象类或接口,也可以是具体类。        Adapter(适配器类):适配器可以调用另一个接口,作为一个转换器,对Adaptee和Target进行适配,适配器类是适配器模式的核心,在对象适配器中,它通过继承Target并关联一个Adaptee对象使二者产生联系。        Adaptee(适配者类):适配者即被适配的角色,它定义了一个已经存在的接口,这个接口需要适配,适配者类一般是一个具体类,包含了客户希望使用的业务方法,在某些情况下可能没有适配者类的源代码

例如:

class Adapter extends Target {      private Adaptee adaptee; //维持一个对适配者对象的引用      public Adapter(Adaptee adaptee) {          this.adaptee=adaptee;      }      public void request() {          adaptee.specificRequest(); //转发调用      }  }  

多个对象适配者情况:
在图中,ScoreOperation 接口充当抽象目标,QuickSort 和 BinarySearch 类充当适配者,OperationAdapter 充当适配器。完整代码如下所示:
这里写图片描述

//抽象成绩操作类:目标接口interface ScoreOperation {    public int[] sort(int array[]); //成绩排序    public int search(int array[],int key); //成绩查找}//快速排序类:适配者class QuickSort {    public int[] quickSort(int array[]) {        sort(array,0,array.length-1);        return array;    }    public void sort(int array[],int p, int r) {        int q=0;        if(p<r) {            q=partition(array,p,r);            sort(array,p,q-1);            sort(array,q+1,r);        }    }    public int partition(int[] a, int p, int r) {        int x=a[r];        int j=p-1;        for (int i=p;i<=r-1;i++) {            if (a[i]<=x) {                j++;                swap(a,j,i);            }        }        swap(a,j+1,r);        return j+1;     }    public void swap(int[] a, int i, int j) {           int t = a[i];           a[i] = a[j];           a[j] = t;       }}//二分查找类:适配者class BinarySearch {    public int binarySearch(int array[],int key) {        int low = 0;        int high = array.length -1;        while(low <= high) {            int mid = (low + high) / 2;            int midVal = array[mid];            if(midVal < key) {  low = mid +1;  }            else if (midVal > key) {  high = mid -1;  }            else {  return 1; //找到元素返回1  }        }        return -1;  //未找到元素返回-1    }}//操作适配器:适配器class OperationAdapter implements ScoreOperation {    private QuickSort sortObj; //定义适配者QuickSort对象    private BinarySearch searchObj; //定义适配者BinarySearch对象    public OperationAdapter() {        sortObj = new QuickSort();        searchObj = new BinarySearch();    }    public int[] sort(int array[]) {  return sortObj.quickSort(array); //调用适配者类QuickSort的排序方法}    public int search(int array[],int key) {  return searchObj.binarySearch(array,key); //调用适配者类BinarySearch的查找方法}}

为了让系统具备良好的灵活性和可扩展性,我们引入了工具类 XMLUtil 和配置文件,其中,XMLUtil 类的代码如下所示:

import javax.xml.parsers.*;import org.w3c.dom.*;import org.xml.sax.SAXException;import java.io.*;class XMLUtil {//该方法用于从XML配置文件中提取具体类类名,并返回一个实例对象    public static Object getBean() {        try {            //创建文档对象            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();            DocumentBuilder builder = dFactory.newDocumentBuilder();            Document doc;                                       doc = builder.parse(new File("config.xml"));             //获取包含类名的文本节点            NodeList nl = doc.getElementsByTagName("className");            Node classNode=nl.item(0).getFirstChild();            String cName=classNode.getNodeValue();            //通过类名生成实例对象并将其返回            Class c=Class.forName(cName);            Object obj=c.newInstance();            return obj;        }           catch(Exception e) {            e.printStackTrace();            return null;        }    }}配置文件 config.xml 中存储了适配器类的类名,代码如下所示:<?xml version="1.0"?>  <config>      <className>OperationAdapter</className>  </config>  编写如下客户端测试代码:class Client {    public static void main(String args[]) {        ScoreOperation operation;  //针对抽象目标接口编程        operation = (ScoreOperation)XMLUtil.getBean(); //读取配置文件,反射生成对象        int scores[] = {84,76,50,69,90,91,88,96}; //定义成绩数组        int result[];        int score;        System.out.println("成绩排序结果:");        result = operation.sort(scores);        //遍历输出成绩        for(int i : scores) {            System.out.print(i + ",");        }        System.out.println();        System.out.println("查找成绩90:");        score = operation.search(result,90);        if (score != -1) {            System.out.println("找到成绩90。");        }        else {            System.out.println("没有找到成绩90。");        }        System.out.println("查找成绩92:");        score = operation.search(result,92);        if (score != -1) {            System.out.println("找到成绩92。");        }        else {            System.out.println("没有找到成绩92。");        }    }}编译并运行程序,输出结果如下:成绩排序结果:50,69,76,84,88,90,91,96,查找成绩90:找到成绩90。查找成绩92:没有找到成绩92

这里写图片描述

0 0