否则,在外面,别人仍然可以使用SingLeton instance = new SingLeton(); 来构造对象。呵呵。 [解决办法]
Java code
public class Singleton { private static Singleton instace = null; // private 修饰,避免外部更改 private Singleton(){} // 隐藏构造函数 public static synchronized Singleton getInstance() { // 同步,避免同时创建多个实例 if (instance == null) { instance = new ... } return instance; }} [解决办法]
[解决办法]
Java code
public class Singleton{ private static Singleton instance = new Singleton(); private SingLeton(){ } public static Singleton getInstance(){ return instance; }}