如何在AOP中实现策略模式
谁能告诉我如何在AOP中实现策略模式?
使用 Spring-AOP 或 AspectJ 的示例将会非常有帮助。
Can anyone tell me how to implement the Strategy Pattern in AOP?
An example using Spring-AOP or AspectJ would be very helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现的最简单的方法是让你的类实现一个空白接口。
然后使用 AspectJ 将实现插入到接口中。
这样,如果您需要更改算法,您只需使用不同的方面即可解决问题。
为此,您可以查看 如何使用类型间。
本文有一些将方法注入接口的很好的例子。
这没有实现策略模式,但基本概念是相同的,可以轻松地从一种算法切换到另一种算法,而无需更改代码的任何其他部分。我能看到的唯一其他方法是使用 DI 并注入一个新的具体类,每个类都具有相同的策略接口,但这超出了问题范围。
以下是一些展示 AOP 功能的链接:
AspectJ 的用途远不止于一些基本的交叉- 消除顾虑。大多数 GoF 设计模式都可以通过使用 AspectJ 轻松实现或停用。
The easiest way I have found is to have your class implement a blank interface.
Then you use AspectJ to insert the implementation into the interface.
This way, if you need to change the algorithm you can just use a different aspect and the problem is solved.
To do this you can look at the manual on how to use inter-type.
This article has some nice examples of injecting methods into an interface.
This is not implementing the Strategy pattern, but the basic concept is the same, make it easy to switch from one algorithm to another, without changing any other part of the code. The only other way I can see of doing this is to use DI and just inject a new concrete class that each has the same interface for the Strategy, but that is outside of the question.
Here are some links to show what can be done with AOP:
AspectJ can be used for a great deal more than just some basic cross-cutting concerns. Most of the GoF design patterns can be easily implemented or retired by using AspectJ.
我认为你把两件事搞混了。
AOP 是围绕“真实”代码实现不同方面的。就像日志记录和验证一样。日志记录本身可以通过使用 DI 容器(如 spring 提供的)来实现,以真正将日志记录委托给正确的实现(策略)。
I think you got two things mixed up.
AOP is about implementing different aspects around the 'real' code. Like logging and validation. The logging itself could be implemented by using a DI container (like offered by spring) to really delegate the logging to the right implementation (strategy).