设计模式之:适配器模式AdapterPattern的实现
- 在面向对象软件系统中,每个类/对象都承担了一定的职责,他们可以相互协作,实现一些复杂的功能;
- 如果系统中存在不兼容的接口,可以通过引入一个适配器来使得原本不兼容的两个类可以一起工作;
- 这里的适配器就像手机的充电器(手机充电器也叫电源适配器),将不适配的220V电转化为可以适配的电,很明显,这个适配器需要和220V电源有一个插头,并且和手机端也要有一个插头;
类图 with StarUML
原有的分数操作接口
internal interface ScoreOperation
{
int[] Sort(int[] arry);
int Search(int[] arry, int key);
}
新的快速排序算法,与原有接口并不适配
public int[] QuickSort(int[] arry)
{
Sort(arry, 0, arry.Length - 1);
return arry;
}
private void Sort(int[] arry, int p, int r)
{
int q = 0;
if (p < r)
{
q = Partition(arry, p, r);
Sort(arry, p, q - 1);
Sort(arry, q + 1, r);
}
}
private int Partition(int[] arry, int p, int r)
{
int x = arry[r];
int j = p - 1;
for (int i = p; i <= r - 1; i++)
{
if (arry[i] <= x)
{
j++;
Swap(arry, j, i);
}
}
Swap(arry, j + 1, r);
return j + 1;
}
private void Swap(int[] arry, int i, int j)
{
int t = arry[i];
arry[i] = arry[j];
arry[j] = t;
}
}
新的二分查找算法,也与原有接口不匹配
public int BinarySearch(int[] arry,int key)
{
int low = 0;
int high = arry.Length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
int midValue = arry[mid];
if (midValue < key)
{
low = mid + 1;
}
else if (midValue > key)
{
high = mid - 1;
}
else
{
return 1;//找到返回1
}
}
return -1;//找不到返回-1
}
}
适配器,将不兼容的接口进行适配;
必须继承自原有的ScoreOperation接口,并将新的算法适配到原有接口中的 方法
internal class OperationAdapter : ScoreOperation
{
private QuickSortClass quickSort;
private BinarySearchClass binarySearch;
public OperationAdapter()
{
quickSort = new QuickSortClass();
binarySearch = new BinarySearchClass();
}
/// <summary>
/// 将BinarySearch()适配到Search()
/// </summary>
/// <param name="arry"></param>
/// <param name="key"></param>
/// <returns></returns>
public int Search(int[] arry, int key)
{
return binarySearch.BinarySearch(arry,key);
}
/// <summary>
/// 将QuickSort()适配到Sort()
/// </summary>
/// <param name="arry"></param>
/// <returns></returns>
public int[] Sort(int[] arry)
{
return quickSort.QuickSort(arry);
}
}
配置文件(使用配置文件,而不是硬编码,符合开闭原则)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="adapter" value="AdapterPattern.OperationAdapter"/>
</appSettings>
</configuration>
客户端(面向接口编程,符合依赖倒置原则)
internal class Program
{
static void Main(string[] args)
{
//面向接口编程,便于扩展
ScoreOperation operation;
//读取配置文件
string adapterType = ConfigurationManager.AppSettings["adapter"];
//用反射生成对象
operation = Assembly.Load("AdapterPattern").CreateInstance(adapterType) as ScoreOperation;
//测试
int[] scores = { 56,88,98,83,76,58,92,68,90};
int[] result = operation.Sort(scores);
Console.WriteLine("成绩排序结果:");
foreach (var item in result)
{
Console.Write(item + ",");
}
int searchResult;
searchResult=operation.Search(result,90);
Console.WriteLine();
if (searchResult == 1) Console.WriteLine("查到成绩90");
else if(searchResult == -1) Console.WriteLine("没有查到成绩90");
searchResult = operation.Search(result, 100);
if (searchResult == 1) Console.WriteLine("查到成绩100");
else if (searchResult == -1) Console.WriteLine("没有查到成绩100");
Console.Read();
}
}
运行结果