策略模式
定义
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.
场景就是在有多个算法的场景下。
例子
这个模式在框架中非常常见,一个典型场景就是在使用线程池的时候:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
最后一个参数RejectedExecutionHandler就是个策略模式,拒绝策略。
Context is a class which uses a Strategy.
Context是个具体的类,上例中,ThreadPoolExecutor就是个context。