(行为型)设计模式——策略模式(strategy)

ps:在以下讲述策略模式中,模仿的场景如下:有一个Dog类,它有两个属性height和weight。现在想利用Sorter类,既可以通过比较height来对Dog进行排序,又可以按照weight对Dog进行排序。类图和代码如下。

在这里插入图片描述
1、Comparator接口(不同于Java 类库中的Comparator接口)

public interface Comparator<T> {
	
	//任何实现Comparator接口的类,都必须实现compare方法
    int compare(T o1,T o2);

}

2、DogHeightComparator类

public class DogHeightComparator implements Comparator<Dog>{

    @Override
    public int compare(Dog o1, Dog o2) {
        if (o1.getHeight()<o2.getHeight()) {return -1;}
        else if (o1.getHeight()>o2.getHeight()) {return 1;}
        return 0;
    }
    
}

3、DogWeightComparator类

public class DogWeightComparator implements Comparator<Dog>{

    @Override
    public int compare(Dog o1, Dog o2) {
        if (o1.getWeight()<o2.getWeight()) {return -1;}
        else if (o1.getWeight()>o2.getWeight()) {return 1;}
        return 0;
    }

}

4、Dog类

public class Dog{

    private int height;
    private int weight;

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public Dog(int height, int weight){
        this.height = height;
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "height=" + height +
                ", weight=" + weight +
                '}';
    }
}

5、Sorter类

public class Sorter<T> {

    //使用选择排序,对传进来的数组进行排序
    public void selectSort(T[] arr, Comparator<T> comparator){

        for (int i = 0; i < arr.length; i++) {

            int minIndex = i;

            for (int j = i+1; j < arr.length; j++) {

                //使用comparator中的compare方法提供的比较策略来进行大小比较
                if (comparator.compare(arr[j],arr[minIndex])==-1){
                    minIndex = j;
                }

            }
            swap(arr,i,minIndex);
        }
    }

    //交换值
    public void swap(T[] arr, int i, int minIndex) {

        T temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;

    }

}

6、Main类(测试)

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {

        Dog[] cats ={new Dog(3,5),new Dog(1,1),new Dog(5,3)};

        Sorter<Dog> sorter = new Sorter<>();

        //使用比较身高来排序的策略
       /* sorter.selectSort(cats,new DogHeightComparator());*/

        //使用比较体重来排序的策略
        sorter.selectSort(cats,new DogWeightComparator());


        System.out.println(Arrays.toString(cats));
    }

}

总结:使用策略模式,在提供不同的比较策略的情况下,最终在不改变Sorter类中的排序方法的情况下,最终改变排序规则。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值