不兼容结构的协调—适配器模式(二)
9.3 完整解决方案
图9-4
[java] view plaincopy
-
//抽象成绩操作类:目标接口
-
interface
ScoreOperation { -
public int[] sort( intarray[]); //成绩排序 -
public int search( intarray[], intkey); //成绩查找 - }
-
-
//快速排序类:适配者
-
class
QuickSort { -
public int[] quickSort( intarray[]) { -
sort(array,0,array.length-1); -
return array; -
} -
-
public void sort( intarray[], intp, intr) { -
int q= 0; -
if(p -
q=partition(array,p,r); -
sort(array,p,q-1); -
sort(array,q+1,r); -
} -
} -
-
public int partition( int[]a, intp, intr) { -
int x=a[r]; -
int j=p- 1; -
for ( inti=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, inti, intj) { -
int t = a[i]; -
a[i] = a[j]; -
a[j] = t; -
} - }
-
-
//二分查找类:适配者
-
class
BinarySearch { -
public int binarySearch( intarray[], intkey) { -
int low 0;= -
int high 1;= array.length - -
while(low <= high) { -
int mid 2;= (low + high) / -
int midVal = array[mid]; -
if(midVal < key) { -
low
= mid +1; - }
-
else if (midVal > key) { -
high
= mid -1; - }
-
else { -
return
1; //找到元素返回1 - }
-
} -
return - 1; -
} - }
-
-
//操作适配器:适配器
-
class
OperationAdapter implementsScoreOperation { -
private QuickSort //定义适配者QuickSort对象sortObj; -
private BinarySearch //定义适配者BinarySearch对象searchObj; -
-
public OperationAdapter() { -
sortObj = new QuickSort(); -
searchObj = new BinarySearch(); -
} -
-
public int[] sort( intarray[]) { -
return
sortObj.quickSort(array); //调用适配者类QuickSort的排序方法 - }
-
-
public int search( intarray[], intkey) { -
return
searchObj.binarySearch(array,key); //调用适配者类BinarySearch的查找方法 - }
- }
[java] view plaincopy
-
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_r("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; -
} -
} - }
[html] view plaincopy