单例模式是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;
}
}