单例模式简介:单例模式属于众多设计模式中的一种,主要用于保证系统中实例有且只有一个。而且可以轻易被外界调用。这也说明了单例模式的三个要点。
- 只能有一个实例在类中。
- 需要自己创建这个实例。
需要提供访问这个实例的方法。
单例模式分为懒汉模式和饿汉模式:
两种模式的特点如下:
饿汉模式:类加载速度慢,运行是获取实例速度快,线程安全。
懒汉模式:类加载速度快,运行时获取实例速度慢,线程不安全。
饿汉模式实现如下:
public class EhanSingleton(){
//1.首先构造方法私有,外界无法通过new来创建实例。
private staic EhanSingleton(){
}
//2.创建自己的实例,实例为类成员变量,类创建是即创建了实例对象。
private static EhanSingleton instance = new EhanSingleton ();
//3提供对外的获取实例的方法
public static EhanSingleton getInstance(){
return instance;
}
}
懒汉模式实现代码如下:
public class LanhanSingleton(){
//1.首先构造方法私有,外界无法通过new来创建实例。
private staic LanhanSingleton(){
}
//2.声明实例变量。变量用private static修饰。
private static LanhanSingleton instance = null;
//3提供对外的获取实例的方法
public static LanhanSingleton getInstance(){
if(instance != null){
instance = new LanhanSingleton ();
}
}
}