简单了解策略模式

什么是策略模式?

策略模式提供生成某一种产品的不同方式

Strategy策略类定义了某个各种算法的公共方法,不同的算法类通过继承Strategy策略类,实现自己的算法

Context的作用是减少客户端和Strategy策略类之间的耦合,客户端只需要调用Context并且传递相应的算法参数,来调用不同的算法,Context的内部实现可以用一个Map<id, Strategy>,在Spring启动的时候,会把Strategy类自动装配进Map

image-20240104171319410

Spring的策略模式

Resource getResource(String location) 根据传入的 location(算法参数)返回一个资源子类(具体算法),如 ClassPathResource 内部定义了解析 xml 的方法

else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
    return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
    try {
       // Try to parse the location as a URL...
       URL url = ResourceUtils.toURL(location);
       return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
    }
    catch (MalformedURLException ex) {
       // No URL -> resolve as resource path.
       return getResourceByPath(location);
    }
}

getInstantiationStrategy().instantiate(),如果需要被反射创建的 bean 的方法没有覆写,直接用无参构造器创建,否则用CGLIB创建。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您想要了解如何使用Java编写策略模式的实现。我可以为您提供一个简单的例子来说明。 首先,我们需要定义一个策略接口,该接口包含所有可能的算法或策略。例如: ``` public interface Strategy { int execute(int a, int b); } ``` 然后,我们需要实现这个接口来提供我们的算法或策略。例如: ``` public class OperationAdd implements Strategy { @Override public int execute(int a, int b) { return a + b; } } public class OperationSubtract implements Strategy { @Override public int execute(int a, int b) { return a - b; } } public class OperationMultiply implements Strategy { @Override public int execute(int a, int b) { return a * b; } } public class OperationDivide implements Strategy { @Override public int execute(int a, int b) { return a / b; } } ``` 接下来,我们需要创建一个策略上下文来调用不同的策略。例如: ``` public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int a, int b) { return strategy.execute(a, b); } } ``` 最后,我们可以通过以下方式使用我们的策略模式: ``` public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubtract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationDivide()); System.out.println("10 / 5 = " + context.executeStrategy(10, 5)); } ``` 输出结果应该为: ``` 10 + 5 = 15 10 - 5 = 5 10 * 5 = 50 10 / 5 = 2 ``` 希望这个简单的例子可以帮助您理解如何使用Java编写策略模式的实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值