SE450: Singleton: Often the singleton is public [20/32] |
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
package singleton.pub4; public abstract class S { private static S instance; static { if ("linux".equals(System.getProperty("os.name"))) instance = new SLinux(); else instance = new SOther(); } public static S get() {return instance;} public abstract int inc(); } final class SLinux extends S { private int i; public int inc() {return ++i;} } final class SOther extends 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.pub4.main; import singleton.pub4.S; public class Main { public static void main (String[] args) { S s = S.get(); System.out.println(s.inc()); System.out.println(s.inc()); } }
You can also use a public method rather than a public field.