首页 > 其他 > 详细

结构型模式之适配器模式

时间:2020-04-08 01:11:17      阅读:74      评论:0      收藏:0      [点我收藏+]

1 定义

  适配器模式,作为连接两个接口的桥梁。这个概念感觉有点那啥,很少用接口的朋友可能就没有什么感觉,经常面向接口编程的朋友比较能产生共鸣,简单来说,就是写一个适配器(转换器)来对接对象。

  使用前提或场景:解决两个已有接口间不兼容问题。Client面向接口编程,而该面向的接口又与第三方接口不兼容,两者又不便于修改,则可用Adapter协调工作

2 模式结构

技术分享图片

 

 

 

包含如下角色:

    1. Target(目标抽象类)
      客户期望的业务接口,可以是具体类,也可以是接口。

    2. Adapter(适配器类)
      适配器类可调用Adaptee接口,以对 Adaptee 和 Target 进行适配,使其协调工作。

    3. Adaptee(适配者类)
      被适配的角色,定义了可工作、已存在、待适配的接口,些情况下甚至没有源代码。

    4. Client(客户类)
      客户类面对目标抽象类进行编程

3 代码

adapter.java文件

package structural.adapter;

public class Adapter implements DataOperation {

  private BinarySearch search;

  private QuickSort sort;

  public Adapter(){

    search = new BinarySearch();

    sort = new QuickSort();

    }

  public void sort(int[] array) {

    sort.quickSort(0,array.length-1,array);

  }

  public int search(int[] array, int key) {

    return search.BinarySearch(0,array.length-1,key,array);

  }

}

BinarySearch.java文件

package structural.adapter;

public class BinarySearch {

  public int BinarySearch(int low, int high, int key, int[] array){

    if(low>high)

      return -1;

    int mid = (low+high)/2;

    if(array[mid] == key)

      return mid;

    int temp = BinarySearch(low,mid-1,key,array);

    if(temp!=-1) return temp;

    temp = BinarySearch(mid+1,high,key,array);

    if(temp!=-1) return temp;

    return -1;

  }

}

Client.java文件

package structural.adapter;

import java.util.Arrays;

public class Client {

  public static void main(String[] args){

    DataOperation operation;

    operation = new Adapter();

    int[] ary = {4,1,1,2,1,9,3,2,1,1};

    operation.sort(ary);

    System.out.println(Arrays.toString(ary));

  }

}

DataOperation.java文件

package structural.adapter;

public interface DataOperation {

  public void sort(int[] array);

  public int search(int[] array, int key);

}

QuickSort.java文件

package structural.adapter;

public class QuickSort {

  public void quickSort(int low, int high, int[] array){

    if(low >= high)

      return;

    int i=low+1,j=high;

    while(i<=j){

      while(i<=high&&array[i]<=array[low])

        i++;

      while(j>low&&array[j]>array[low])

        j--;

      if(i<j)

        switchIndex(i,j,array);

    }

    switchIndex(--i,low,array);

    quickSort(low,i-1,array);

    quickSort(i+1,high,array);

  }

  private void switchIndex(int index1, int index2, int[] array){

    int temp = array[index1];

    array[index1] = array[index2];

    array[index2] = temp;

  }

}

结构型模式之适配器模式

原文:https://www.cnblogs.com/yimugoi/p/12657322.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!