单例模式单例模式是一种常见的设计模式,
单例模式分两种:懒汉式单例、饿汉式单例。 单例模式有一下特点:
1、单例类只能有一个实例。
2、单例类必须自己自己创建自己的唯一实例。 3、单例类必须给所有其他对象提供这一实例。
一、饿汉式单例在类被加载的时候,唯一实例已经被创建。这个设计模式在Java中容易实现,在别的语言中难以实现。 单例模式-懒汉式单例
代码:
public class EagerSingleton {
private static final EagerSingleton m_instance = new EagerSingleton();
private EagerSingleton() { }
public static EagerSingleton getInstance()
{
return m_instance;
}
当类被加载的时候,static 类型的m_instance就会被事例化,保证的单利模式的自动创建条件,他是常量,保证了值不变,即保证了对象的唯一;事例的创建调用了私有的构造方法,构造方法私有保证了外界不能直接调用。
二、懒汉式单例类:
代码:
public class LazySingleton
{
private static LazySingleton m_instance = null;
private LazySingleton() { }
synchronized public static LazySingleton getInstance()
{
if(m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance; }
}
}