源码中的设计模式之策略设计模式
前言
这次又水到了策略模式,这个简单~。
(1)所谓的策略模式就是将既有的多个算法分别封装到不同的类下,并且这些算法都是对同一个问题提出不同的解决方式。
(2)并且这些类都必须实现同一个接口。
当用户调用该方法的时候,会根据用户传入的参数选择合适的算法,输出更优的解给用户.就是这么个意思~~
策略模式下的源码
DefaultEventExecutorChooserFactory
public final class DefaultEventExecutorChooserFactory implements EventExecutorChooserFactory {
public static final DefaultEventExecutorChooserFactory INSTANCE = new DefaultEventExecutorChooserFactory();
private DefaultEventExecutorChooserFactory() {
}
public EventExecutorChooser newChooser(EventExecutor[] executors) {
return (EventExecutorChooser)(isPowerOfTwo(executors.length) ? new DefaultEventExecutorChooserFactory.PowerOfTowEventExecutorChooser(executors) : new DefaultEventExecutorChooserFactory.GenericEventExecutorChooser(executors));
}
private static boolean isPowerOfTwo(int val) {
return (val & -val) == val;
}
private static final class GenericEventExecutorChooser implements EventExecutorChooser {
private final AtomicInteger idx = new AtomicInteger();
private final EventExecutor[] executors;
GenericEventExecutorChooser(EventExecutor[] executors) {
this.executors = executors;
}
public EventExecutor next() {
return this.executors[Math.abs(this.idx.getAndIncrement() % this.executors.length)];
}
}
private static final class PowerOfTowEventExecutorChooser implements EventExecutorChooser {
private final AtomicInteger idx = new AtomicInteger();
private final EventExecutor[] executors;
PowerOfTowEventExecutorChooser(EventExecutor[] executors) {
this.executors = executors;
}
public EventExecutor next() {
return this.executors[this.idx.getAndIncrement() & this.executors.length - 1];
}
}
}
上面源码中GenericEventExecutorChooser跟PowerOfTowEventExecutorChooser就是两个包装不同算法的类,都实现了统一的接口。
EventExecutorChooserFactory
package io.netty.util.concurrent;
public interface EventExecutorChooserFactory {
EventExecutorChooserFactory.EventExecutorChooser newChooser(EventExecutor[] var1);
public interface EventExecutorChooser {
EventExecutor next();
}
}
到底选择哪个算法根据executors这个数组是否是2的次幂来确定。