策略设计模式与c语言中的函数指针

在C语言中有一个非常重要的概念-函数指针,其最重要的功能是实现回调函数(指函数先在某处注册,而它将在稍后某个需要的时候被调用)在java语言中没有指针的概念,但是可以利用接口和指针实现类似的功能,具体而言,应先定义一个接口,最后把这个实现类的一个对象作为参数传递给调用程序,调用程序通过这个参数来调用指定的函数,从而实现回调函数(这里接口就像是注册的地方,实现类就是“注册人”,当实现类作为形参时,就是在需要的时候)

package strateryDemo;

import java.util.Arrays;

//这个在Think in java 也有类似的例子
interface IntCompare
{
    public int cmp(int a, int b);
}

class Cmp1 implements IntCompare
{

    @Override
    public int cmp(int a, int b)
    {
        if (a > b)
        {
            return 1;
        } else if (a < b)
        {
            return -1;
        }

        return 0;
    }
}

class cmp2 implements IntCompare
{

    @Override
    public int cmp(int a, int b)
    {
        if (a > b)
        {
            return -1;
        } else if (a < b)
        {
            return 1;
        }

        return 0;
    }

}

public class StrateryTest
{
    public static void insertSort(int[] a, IntCompare cmp)
    {
        if (a != null)
        {
            for (int i = 1; i < a.length; i++)
            {
                int temp = a[i], j = i;
                if (cmp.cmp(a[j - 1], temp) == 1)
                {
                    while (j >= 1 && cmp.cmp(a[j - 1], temp) == 1)
                    {
                        a[j] = a[j - 1];
                        j--;
                    }
                }
                a[j] = temp;
            }

        }
    }

    public static void main(String[] args)
    {
        int[] arr1 = { 2, 4, 56, 72, 1, 54, 68798 };
        insertSort(arr1, new Cmp1());
        System.out.println(Arrays.toString(arr1));
        int[] arr2 = { 223, 42, 56, 72, 1, 54, 68798 };

        insertSort(arr2, new cmp2());
        System.out.println(Arrays.toString(arr2));
    }
}

 

转载于:https://www.cnblogs.com/rocky-AGE-24/p/5769965.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值