开发者

Pattern for C-style static variables in Java?

What is the best way to create a C-style static variable in Java (local to a method)?

I have a method in which I need to calculate a variable only once, and do not need to recalculate it for the lifetime of the object.

I understand that I could create a final field, but this variable may not be required in all cases and would only be required if this method in question is called at all by the client.

Any pointers on how开发者_Go百科 I could achieve this?


C++ static locals are equivillant to static fields with lazy initialization.

C++:

class Example {
 public:
  void method() {
    static Something something;
  }
};

Java:

public class Example {
    private static Something something;
    public void method() {
        if (something == null) something = new Something();
    }
}


I would use lazy initialization wherever this thing is called. Local memoization if well thought through creates less chaos than distributing it over multiple classes.

If you need to share even then a lazy static initialization in a for the rest stateless service is better than a Singleton. If caching/memoization is local (and appropriate) it does not break the 'stateless' mental picture which helps keep code clean.

However caching/memoization is a pain to test. But mocking stateless beans is trivial, and independently verifying the cache works, is easy too.


local to a method
for the lifetime of the object

For me those two sentences are mutually exclusive in the java world. You either want a variable local to a method or an instance variable. Judging by what you said you want the latter. To initialize it you can use, as someone already said, the lazy loading pattern which will initialize it when, and only when, you need it. The downside would be checking in other methods whether it was initialized.

Doing things in Java the C way isn't the best idea imho.


Use the Lazy Load pattern.


I think you may be referring to a "lazy cache" type of strategy. Like this:

class LazyCacheExample {

    Integer x = null;

    public Integer calculateX() {
        // if x has not been calculated yet, calculate it now
        if (null == this.x) {
            // TODO consider thread safety here... 
            this.x = 2+2; 
        }

        // otherwise return the calculated object
        return this.x;
    }   
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜