SE450: Singleton: (Polymorphic) Singleton [15/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
package singleton.state;
public class S {
  private S() {}
  static private SState state;
  static {
    if ("linux".equals(System.getProperty("os.name"))) {
      state = new SLinux();
    } else {
      state = new SOther();
    }
  }
  static public int inc() { 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.state.main;
import singleton.state.S;
public class Main {
  public static void main (String[] args) {
    System.out.println(S.inc());
    System.out.println(S.inc());
  }
}

Previous pageContentsNext page