- 单例模式
单例模式确保一个类只有一个对象,提供一个全局的访问点。
构造方法:提供一个私有类变量、类私有构造方法、公有静态方法
public class Singleton {
private Singleton instance = null;
private Singleton(){
}
public Singleton getInstance(){
if(instance == null)
{
instance = new Singleton();
}
return instance;
}
private static Singleton instance = new Singleton();
private static Singleton instance = null;
public static synchronized Singleton getInstance(){
if(instance == null)
{
instance = new Singleton();
}
return instance;
}
private volatile static Singleton instance = null;
public static Singleton getInstance(){
if(instance == null)
{
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
public enum EnumSingleton {
INSTANCE;
public EnumSingleton getInstance(){
return INSTANCE;
}
}