SE450: Singleton: Lazy Instantiation [16/32] Previous pageContentsNext page

file:S.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package singleton.lazy;
public class S {
  private S() {}
  static private SState state;
  static public int inc() {
    if (state == null) {
      if ("linux".equals(System.getProperty("os.name"))) {
        state = new SLinux();
      } else {
        state = new SOther();
      }
    }
    return state.inc();
  }

  static private interface SState {
    public int inc();
  }
  static private class SLinux implements SState {
    private int i;
    public int inc() {return ++i;}
  }
  static private class SOther implements SState {
    private int i;
    public int inc() {return --i;}
  }
}

file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
package singleton.lazy.main;
import singleton.lazy.S;
public class Main {
  public static void main (String[] args) {
    System.out.println(S.inc());
    System.out.println(S.inc());
  }
}

In dynamically initialized languages, lazy instantiation is usually silly.

Previous pageContentsNext page