单例模式:
单例模式是一种常用的且非常简单的一种设计模式。它的核心结构只有一个被称为单例类的特殊类。通过单例模式可以保证系统只有一个实例而且容易被外界访问,从而节约系统资源,减少gc的回收内存的压力,避免了一些引起业务逻辑错误的因素。
(单例模式类图)
单例模式一般有三种模式:
① 懒汉式
public class Singleton {
private static Singleton singleton;
/**
*构造器
*
*@authorzhaozb
*@timeOct12,20133:41:54PM
*/
private Singleton() {}
/**
*获取实例
*
*@return
*@authorzhaozb
*@timeOct12,20133:42:11PM
*/
public synchronized Singleton getInstance() {
if(singleton ==null){
singleton =new Singleton();
}
return singleton;
}
}
在涉及到多线程时需要加Synchronized字段。
② 饿汉式
private static Singleton instance =new Singleton();
// static {
// instance = new Singleton();
// }
/**
*构造器
*/
private Singleton(){};
/**
*得到实例
*
*@return
*@authorzhaozb
*@timeOct12,20133:52:43PM
*/
public static Singleton getInstance(){
return instance;
}
③ 双重锁定
public class Singleton {
private static Singleton instance;
/**
*私有构造器
*
*@authorzhaozb
*@timeOct12,20133:53:58PM
*/
private Singleton(){};
public static Singleton getInstance(){
if(instance ==null){
synchronized(Singleton.class){
if(instance ==null){
instance =new Singleton();
}
}
}
return instance;
}
}