策略模式及应用

定义

在 GoF 的《设计模式》一书中,它是这样定义的:

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

大体意思就是:定义一组可互相替换的算法,可以独立与客户端变化。

策略模式解耦了策略的定义、创建和使用。

1、策略定义
public interface Strategy {
  void algorithm();
}

public class StrategyA implements Strategy {
  @Override
  public void  algorithm() {
    //具体的算法...
  }
}

public class StrategyB implements Strategy {
  @Override
  public void  algorithm() {
    //具体的算法...
  }
}
2、策略的创建

策略类一般是无状态的,可以被共享使用。我们可以使用工厂类实现。

这里的if-else可以使用查表法替换,如存到一个Map。

public class StrategyFactory {
  public static Strategy getStrategy(String type) {
    if (type.equals("A")) {
      return new StrategyA();
    } else if (type.equals("B")) {
      return new StrategyB();
    }

    return null;
  }
}
3、策略的使用

主要是根据配置、用户输入等选择对应的策略,客户端(调用方)只需传入对应参数即可。

应用

1、spring Aop

根据config返回Jdk动态代理或是Cglib代理

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

	@Override
	public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
		if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
			Class<?> targetClass = config.getTargetClass();
			if (targetClass == null) {
				throw new AopConfigException("TargetSource cannot determine target class: " +
						"Either an interface or a target is required for proxy creation.");
			}
			if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
				return new JdkDynamicAopProxy(config);
			}
			return new ObjenesisCglibAopProxy(config);
		}
		else {
			return new JdkDynamicAopProxy(config);
		}
	}
2、订单系统根据不同渠道(微信、支付宝、银联、在线余额等),计算金额
posted @ 2020-05-21 17:24  walterlee  阅读(239)  评论(0编辑  收藏  举报