單例模式是java常見額簡單設計模式。使用場景是當程序運行中同時會有多處調用同一類型對象,並對同一資源進行操作且資源需要共享時,可以使用該模式。
1 懶漢模式,線程不安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. 懶漢模式,線程安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
或者
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
synchronized(this){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
3.枚舉單例模式public enum Singleton {
INSTANCE,OHTER;
public void dosomething(){
System.out.println("------------");
}
}
4. 餓漢模式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
5. 內部類單例模式
public class Singleton {
private Singleton (){}
class SingletonFactory{
public final static INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SIngletonFactory.INSTANCE;
}
}