设计模式,以便在调用静态方法之前始终调用静态 init 方法
我有一个要求,在调用类中的任何静态方法之前,我必须调用一些初始化方法。
现在的问题是,每当我向该类添加新的静态方法时,我都会忘记调用该初始化方法,我想知道是否有任何设计模式可以解决这个问题。我希望每当从类调用静态方法时总是调用初始化方法。
I have requirement in which, I have to call some initializing method before the call of any static method in the class.
Now the problem is that whenever i add new static method to that class, I forget to call that initializing method, I was wondering if there any design pattern to solve this problem. I want the initializing method is always called whenever a static method is called from the class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 具有静态初始化块。像这样的东西:
Java has static initialization blocks. Something like this:
对于这个问题,AOP 可能有点大材小用了。您可能想要尝试的是将每个静态方法委托给另一个类,并将初始化代码添加到该类的构造函数中。类似于:
这至少解决了忘记调用初始化代码的问题。
也就是说,这看起来像: https://meta.stackexchange.com/questions/66377 /xy-问题是什么
您能退一步告诉我们为什么您需要这个吗?
AOP might be an overkill for this problem. What you may want to try is to delegate each of the static methods to another class and add the initialization code to the constructor of that class. Something like:
This atleast solves the problem of forgetting to put in the call to init code.
That said, this looks like: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
Can you step back and tell us why you need this?
像 Spring AOP 这样的东西很好地解决了 Java 的这种情况。它使用 AspectJ 注释 来制作内容稍微简单一点,虽然我个人认为AOP相当复杂。
Something like Spring AOP addresses this situation pretty well for Java. It uses AspectJ annotations to make things a little simpler, although personally I think AOP is fairly complex.