适配器模式实例

题目

/**
 * 现有一个接口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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值