// hiding/Lunch.java // Demonstrates class access specifiers. Make a class // effectively private with private constructors: class Soup1 { private Soup1() {} public static Soup1 makeSoup() { // [1] return new Soup1(); } } class Soup2 { private Soup2() {} private static Soup2 ps1 = new Soup2(); // [2] public static Soup2 access() { return ps1; } public void f() {} } // Only one public class allowed per file: public class Lunch { void testPrivate() { // Can't do this! Private constructor: //- Soup1 soup = new Soup1(); } void testStatic() { Soup1 soup = Soup1.makeSoup(); } void testSingleton() { Soup2.access().f(); } }
为什么private构造方法就不能在别的类new对象了,但是可以在自身类new,原因就是private方法是类级访问的。这就是单例的大部分思路,下面的链接是我之前总结的几种单例实现。