Strategy策略模式

定义

Strategy design pattern is one of the Gang of Four (GOF) design patterns. Strategy design pattern defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior

一个功能,替换不同的实现方法;
功能 1.....N 实现方法

类图

image.png
  • Context: 用来操作策略的接口;
  • Strategy: 策略接口
  • ConcreteStrategy: 具体的策略;可进行替换的就是这部分内容
  • Tip:策略的实现是一种多态的应用,掌握多态是实现设计模式的关键。

适用场景

一个功能需要提供不同的实现方法的时候;
比如java中的compare可以写一个自己的实现,来替换原有的compare;Person可以使用age来比较,也可以使用weight来进行比较;

Java中的Comparator

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * description
 * </P>
 *
 * @author: zhangss
 * @since: 2020-07-01
 **/
public class Person {
    public int age;
    public int weight;

    private Person(int age, int weight){
        this.age = age;
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "age: " + age + " weight: " + weight;
    }

    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(16, 120));
        personList.add(new Person(11, 54));
        personList.add(new Person(30, 100));

        System.out.println(personList);

        personList.sort((o1, o2)->{
            if(o1.age > o2.age){
                return 1;
            }
            return -1;
        });

        System.out.println("sort by age: " + personList);

        personList.sort((o1, o2)->{
            if(o1.weight > o2.weight){
                return 1;
            }
            return -1;
        });

        System.out.println("sort by weight: " + personList);
    }
}
// 运行结果
[age: 16 weight: 120, age: 11 weight: 54, age: 30 weight: 100]
sort by age: [age: 11 weight: 54, age: 16 weight: 120, age: 30 weight: 100]
sort by weight: [age: 11 weight: 54, age: 30 weight: 100, age: 16 weight: 120]

ThreadPool 拒绝策略

java提供了4种默认的拒绝策略,当我们需要实现自己的拒绝策略时,实现RejectedExecutionHandler口中的rejectedExecution方法。将线程池的拒绝策略设置为自己的拒绝策略即可。

/**
 * A handler for tasks that cannot be executed by a {@link ThreadPoolExecutor}.
 *
 * @since 1.5
 * @author Doug Lea
 */
public interface RejectedExecutionHandler {
    void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
public class MyRejectedPolicy implements RejectedExecutionHandler {
    @Override    
    void rejectedExecution(Runnable r, ThreadPoolExecutor executor){
        // 具体的拒绝策略
    }
}
// 设置拒绝策略
executor.setRejectedExecutionHandler(new MyRejectedPolicy());

优点

  • 算法可以自由切换;
  • 避免使用多重条件判断;
  • 扩展性良好

缺点

  • 策略类会增多;
  • 所有策略类都需要对外暴露
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。