开发者

design pattern so that a static init method is always called before a call to static method

开发者 https://www.devze.com 2023-02-27 04:27 出处:网络
I have requirement in which, I have to call some initializing method before the call of any static method in the class.

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 w开发者_运维技巧henever a static method is called from the class.


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:

class StaticClass {
    public static void m1 () {
      new Worker().m1();
    }
    public static void m2 () {
      new Worker().m2();
    }
}

class Worker {
   public Worker() {
     intialize();
   }
   public void m1() {
     // Real m1 work
   }
   public void m2() {
     // Real m2 work
   }
}

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?


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.


Java has static initialization blocks. Something like this:

public class SomeClass {
   static {
      // Your code here
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号