SE450: Singleton: Often the singleton is public [18/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
package singleton.pub2;
public interface S {
  public static final S instance = SFactory.newS();
  public int inc();
}
class SFactory {
  static S newS() {
    if ("linux".equals(System.getProperty("os.name")))
      return new SLinux();
    else
      return new SOther();
  }
}
final class SLinux implements S {
  private int i;
  public int inc() {return ++i;}
}
final class SOther implements S {
  private int i;
  public int inc() {return --i;}
}

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

Sometimes you can't do everything in an initializer expression. In this case, you may need a static method.

Previous pageContentsNext page