题目
/**
* 现有一个接口DataOperation定义了排序方法sort(int[])
* 和查找方法search(int[], int),
* 已知类QuickSort的quickSort(int[])方法实现了快速排序算法,
* 类BinarySearch 的binarySearch(int[], int)方法实现了二分查找算法。
* 试使用适配器模式设计一个系统,
* 在不修改源代码的情况下将类QuickSort和类BinarySearch的方法适配到
* DataOperation接口中。绘制类图并编程实现。
* */
类图
代码实现
接口 DataOperation
package com.yuzhyun.test7;
public interface DataOperation {
void sort(int[] array);
int binarySearch(int[] array,int key);
}
适配器
package com.yuzhyun.test7;
public class DataOperationAdapter implements DataOperation{
@Override
public void sort(int[] array) {
new QuickSort().sort(array);
}
@Override
public int binarySearch(int[] array, int key) {
return new BinarySearch().binarySearch(array, key);
}
}
客户类Client
import com.yuzhyun.util.XMLUtil;
public class Client {
public static void main(String[] args) {
int array[]={2,1,3,4,5};
int key=3;
DataOperation dataOperation= (DataOperation) XMLUtil.getBean("configTest7.xml", "com.yuzhyun.test7.");
dataOperation.sort(array);
int index =dataOperation.binarySearch(array, key);
}
}
配置文件读取类XMLUtil
package com.yuzhyun.util
import java.io.File
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import org.w3c.dom.Document
import org.w3c.dom.Node
import org.w3c.dom.NodeList
public class XMLUtil {
public static Object getBean(String configFileName,String packageName) {
try {
DocumentBuilderFactory dFactory = DocumentBuilderFactory
.newInstance()
DocumentBuilder builder = dFactory.newDocumentBuilder()
Document document
//配置文件放在项目的根目录下,不是放在src目录下
document=builder.parse(new File(configFileName))
//获取包含类名的节点
NodeList nodeList=document.getElementsByTagName("className")
Node node= nodeList.item(0).getFirstChild()
String cName=node.getNodeValue().trim()
//通过类名生成实例对象并将其返回
//如果没有包名,会报错java.lang.ClassNotFoundException:
Class class1=Class.forName(packageName+cName)
Object object=class1.newInstance()
return object
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace()
return null
}
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<config>
<className>DataOperationAdapter</className>
</config>