Strategy 策略模式

策略模式

Strategy 策略模式 - 图1

  • 应用场景
    • comparator
    • comparable
      在java中Comparator接口就是运用的策略模式。在Arrays工具类中的sort排序方法中,第一个参数是传入待排序的数组,第二个参数就是Comparator接口,我们可以通过Comparator接口不同的实现指定不同的排序策略,这个就是策略模式。 ```java

public class test { public static void main(String[] args) throws InterruptedException { Dog[] dogs = {new Dog(1,11),new Dog(3,13),new Dog(2,12)}; Arrays.sort(dogs,(o1,o2)->{ if(o1.getAge()o2.getAge()) return 1; return 0; }); System.out.println(Arrays.toString(dogs)); } } class Dog{ private String name; private int age; private int height; public Dog(int a,int b){ this.age = a; this.height = b; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } @Override public String toString() { return “Dog{“ + “name=’” + name + ‘\’’ + “, age=” + age + “, height=” + height + ‘}’; } } ```