设计模式——适配器模式

作者:haibiscuit

时间:2019:3:13

您的star是我不断前行的动力

https://github.com/haibiscuit

转载请说明出处

:适配器模式

   定义:将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

   使用场景:

        1、美国电器 110V,中国 220V,就要有一个适配器将 110V 转化为 220V2JAVA JDK 1.1 提供了 Enumeration 接口,而在 1.2 中提供了 Iterator 接口,想要使用 1.2 JDK,则要将以前系统的 Enumeration 接口转化为 Iterator 接口,这时就需要适配器模式

   示例:以下使用c#的方式演示(看结构和思路,主要为了演示开闭原则的实现)

       //抽象成绩操作类,充当目标接口

       interface ScoreOperation{

          int [] Sort(int []array);    //成绩排序

          int Search(int [] array,int key);

       }

       //快速排序类,充当适配者

       class  QuickSortClass{

           public int[] QuickSort(int []array){

               //内部函数的调用,考虑的很nice

               Sort(array,0,array.Lenrth-1);

               return array;

           }

           //这里是具体操作的函数,真的很nice

           public void Sort(int []array,int p,int r){

           }

       }

       //二分查找类,充当适配者

       class  BinarySearchClass{

           //这里参数和接口中的参数是相同的

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

           return 0;

           }

       }

       //操作适配者,充当适配器

       class  OperationAdapter:ScoreOperation{

           private  QuickSortClass  sortObj;

           private  BinarySearchClass  searchObj;

           public OperationAdapter(){

               sortObj = new QuickSortClass();

               searchObj = new BinarySearchClass();

           }

           @Override

           public int [] Sort(int [] array){

               sortObj.QuickSort(array);   //调用适配者类的排序方法

           }

           @Override

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

           //调用适配者类BinarySearchClass

               return searchObj.BinarySearch(array,key);

           }

       }

       //配置App.config,演示开闭原则

       <?xml version = "1.0" encoding = "utf-8"?>

       <configuration>

           <appSetting>

             <add key = "adapter" value="AdapterSample.Operationdapter"

           <appSetting>           

       </configuration>

        class Test{    //这里使用的是c#

            static void Main(string){

                ScoreOperation operation;

                //读取配置文件

                string adapterType = ConfigurationManager.AppSettings("adapter");

                //反射生成实例

                operation = (ScoreOperation) Assembly.Load("AdapterSample").CreateInstance(adapterType);

                int []scores = {84,76,50,69};

                int []result;

                int score;

                result = operation.Sort(scores);  //排序

                operation.Search(result,90);  //查找成绩

            }

        }

   

   总结:

       1.要搞清楚适配器和适配者之间的关系

       2.另外,注意这里的开闭原则的实现思路

       3.可以看到,适配器和适配者,都有相同的行为,所以可以实现适配器来操作适配者。

原文地址:https://www.cnblogs.com/haibiscuit/p/10526886.html