<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span>
单例模式的英文原文是:Ensure a class has only one instance, and provide a global point of access to it.意思是,确保一个类只有一个实例,并向整个系统提供这个实例。单例模式主要是确保只有一个实例存在。在java语言中有两种表现形式:
饿汉式单例:类加载时就进行实例化。
package com.zz.singleton;
/**
* 饿汉单例
* @author txxs
*
*/
public class HungrySingleton {
//类加载时就进行实例化
private static HungrySingleton m_instance = new HungrySingleton();
//构造方式私有化,保证外界无法直接实例化
private HungrySingleton(){}
//通过以下方法获取实例对象
public static HungrySingleton getInstance(){
return m_instance;
}
}
懒汉式单例:第一次引用类时,才将对象实例化。
package com.zz.singleton;
/**
* 懒汉单例
* @author txxs
*
*/
public class LazySingleton {
//第一次引用类时,才进行对象实例化
private static LazySingleton m_instance = null;
//将构造函数显示的私有化,确保外界无法直接实例化
private LazySingleton(){}
//方法同步,防止两个线程同时访问 m_instance
synchronized public static LazySingleton getInstance(){
if(m_instance == null){
m_instance = new LazySingleton();
}
return m_instance;
}
}
单例模式的优点:
1、只有一个实例,减少内存开支。
2、减少系统的性能开销。
3、可以避免对同一个资源的同时操作。
单例模式的缺点:
无法创建子类,拓展困难。
哈哈,自己写了个代码,参考了一下大神的,互相学习互相进步,下载