设计模式 - 策略模式

87 阅读1分钟

策略模式

对象的某个行为,在不同场景中有不同的实现方式,这样就可以将这些实现方式定义成一组策略每个实现类对应一个策略,在不同的场景使用不同的实现类,并且可以自由切换策略。

public static void serviceImpl() {
    TestModel3[] model = {
            new TestModel3("律师", 30, "男"),
            new TestModel3("小西", 17, "男"),
            new TestModel3("大黄", 19, "男"),
            new TestModel3("中介", 15, "男")};
    new Sore().sore(model, new Comparable());
  }
    
-   Lambda简化
    new Sore().sore(model, (obj1, obj2) -> {
        if (obj1 instanceof TestModel3 && obj2 instanceof TestModel3) {
            TestModel3 model11 = (TestModel3) obj1;
            TestModel3 model21 = (TestModel3) obj2;
            return model11.getAge() - model21.getAge();
        }
        return null;
    });
}
/**
 * @Author LWL
 * @Date 2022/8/16 0:31
 * @TODO 策略类
 */
@FunctionalInterface                     
public interface Comparator {
    Integer compare(Object obj1, Object obj2);
}
public class Comparable implements Comparator {
    public Integer compare(Object obj1, Object obj2) {
        if (obj1 instanceof TestModel3 && obj2 instanceof TestModel3) {
            TestModel3 model1 = (TestModel3) obj1;
            TestModel3 model2 = (TestModel3) obj2;
            return model1.getAge() - model2.getAge();
        }
        return null;
    }
}
public class Sore {
    public void sore(TestModel3[] model, Comparator comparator) {
        for (int i = 0; i < model.length; i++) {
            for (int j = 0; j < model.length - 1; j++) {
                if (comparator.compare(model[j], model[j + 1]) > 0) {
                    TestModel3 temp = model[j];
                    model[j] = model[j + 1];
                    model[j + 1] = temp;
                }
            }
        }
    }
}

优缺点

优点

  • 策略模式提供了可以替换继承关系的办法。
  • 使用策略模式可以避免使用多重条件转移(if - else)语句。

缺点

  • 策略模式将造成产生很多策略类,可以通过使用享元模式在一 定程度上减少对象的数量。
  • 所有的策略类都需要对外暴露,上层模块必须知道有哪些策略,然后才能决定使用哪一个策略