SE450: Singleton: Often the singleton is public [17/32] |
file:S.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
package singleton.pub; public interface S { public static final S instance = ("linux".equals(System.getProperty("os.name"))) ? new SLinux() : new SOther(); public int inc(); } 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.pub.main; import singleton.pub.S; public class Main { public static void main (String[] args) { S s = S.instance; System.out.println(s.inc()); System.out.println(s.inc()); } }
If you make the singleton field public, then it should be final.
If a field is final, then it must be assigned in the initializer.