日期:2014-05-20 浏览次数:20822 次
public class ReadWriteTextFile { private static ReadWriteTextFile rwt; public static ReadWriteTextFile getRWT(){ if(null==rwt){ rwt=new ReadWriteTextFile(); } return rwt; } }
------解决方案--------------------
public enum ReadWriteTextFile { Instance; }
------解决方案--------------------
static {
....
}
这样就行了,何必非得需要时才new呢?我只关注结果。现在内存那么便宜。
------解决方案--------------------
单例模式应该是只返回一次一个类的实例 static静态块如何返回一个类的实例呢 因为不能把所有代码方法都写在静态块里吧
------解决方案--------------------
接分得
------解决方案--------------------
public class SingleTon { private static SingleTon singleTon = new SingleTon(); private SingleTon(){}; public static SingleTon getInstance() { return singleTon; } }
------解决方案--------------------
class SingleTon2 { private static SingleTon2 singleTon; static { singleTon = new SingleTon2(); } private SingleTon2(){}; public static SingleTon2 getInstance() { return singleTon; } }
------解决方案--------------------
class SingleTon3 { private static SingleTon3 singleTon3 = null; public synchronized SingleTon3 getInstance() { if (singleTon3 == null) { singleTon3 = new SingleTon3(); } return singleTon3; } }
------解决方案--------------------
if (instance == null) {
synchronized (instance) {
if (instance == null) {
instance = new XXX();
}
}
}
return instance;
大概这么写 没写过 看人家差不多是这么写得
双重检查是啥。。。
------解决方案--------------------
public class Singleton { private static Singleton instance; private Singleton(){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }