单例模式
Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
一、在很多操作中,比如建立目录 、数据库连接都需要这样的单线程操作。
还有,singleton能够被状态化;这样,多个单态类在一起就可以作为一个状态仓库一样向外提供服务,比如,你要论坛中的帖子计数器,每次浏览一次需要计数,单态类能否保持住这个计数,并且能synchronize的安全自动加1,如果你要把这个数字永久保存到数据库,你可以在不修改单态接口的情况下方便的做到。
另外方面,Singleton也能够被无状态化。提供工具性质的功能,
Singleton模式就为我们提供了这样实现的可能。使用Singleton的好处还在于可以节省内存,因为它限制了实例的个数,有利于Java垃圾回收(garbage collection)。
我们常常看到工厂模式中类装入器(class loader)中也用Singleton模式实现的,因为被装入的类实际也属于资源。
如何使用单例模式
一般Singleton模式通常有几种形式:
public class Singleton {
private Singleton(){}
//在自己内部定义自己一个实例,是不是很奇怪?
//注意这是private 只供内部调用
private static Singleton instance = new Singleton();
//这里提供了一个供外部访问本class的静态方法,可以直接访问
public static Singleton getInstance() {
return instance;
}
}
第二种形式:
public class Singleton {
private static Singleton instance = null;
public static synchronized Singleton getInstance() {
//这个方法比上面有所改进,不用每次都进行生成对象,只是第一次
//使用时生成实例,提高了效率!
if (instance==null)
instance=new Singleton();
return instance;
}
}
使用Singleton.getInstance()可以访问单态类。
上面第二中形式是lazy initialization,也就是说第一次调用时初始Singleton,以后就不用再生成了。
注意到lazy initialization形式中的synchronized,这个synchronized很重要,如果没有synchronized,那么使用getInstance()是有可能得到多个Singleton实例。关于lazy initialization的Singleton有很多涉及double-checked locking (DCL)的讨论。
一般认为第一种形式要更加安全些。
使用单例模式注意事项:
有时在某些情况下,使用Singleton并不能达到Singleton的目的,如有多个Singleton对象同时被不同的类装入器装载;在EJB这样的分布式系统中使用也要注意这种情况,因为EJB是跨服务器,跨JVM的。
Singleton模式看起来简单,使用方法也很方便,但是真正用好,是非常不容易,需要对Java的类 线程 内存等概念有相当的了解。
二、实战
1.饿汉式单例
// 单例模式 (饿汉式单例)
public class Singleton {
// 1. 把构造方法变为私有,这样就限制了其它类创建Singleton的实例
private Singleton(){
}
// 2. Singleton类自己创建唯一的一个实例
private static Singleton singleton = new Singleton();
// 3. 提供一个公共方法返回此唯一实例
public static Singleton getInstance() {
return singleton;
}
}
2.懒汉式单例
package singleton;
// 单例模式 (懒汉式单例) 刚开始不创建,第一次用到时才创建
public class Singleton {
// 把构造方法变为私有
private Singleton() {
}
private static Singleton singleton = null; // 设为volatile保证它的可见性
// 潜在问题, 需要考虑线程安全, 可以使用synchronized来解决
public static synchronized Singleton getInstance() { // 锁住了Singleton.class
// 先判断是不是第一次使用singleton(是否为null)
if( singleton == null ) { // 线程1. null // 线程2. null
singleton = new Singleton();
}
return me;
}
}
3.double-checked locking 线程更加安全高效
public class Singleton {
// 把构造方法变为私有
private Singleton() {
}
private static volatile Singleton singleton = null; // 设为volatile保证它的可见性
// double check 方式
public static Singleton getInstance() {
if( singleton == null ) {
// 优化,进一步缩小了synchronized的范围,仅在第一次调用getInstance方法时才会同步
synchronized (Singleton.class) {
if( singleton == null ) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
4.更优雅的写法(effective java)
package singleton;
// 懒汉式单例,更优雅的写法 effective java
public class Singleton {
private Singleton() {
System.out.println("Singleton 构造方法被调用");
}
private static class Holder {
private static final Singleton singletonInstance = new Singleton();
}
public static Singleton getInstance() {
return Holder.singletonInstance;
}
public static void test() {
System.out.println("test");
}
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton3 s = Singleton.getInstance();
System.out.println(s1 == s2);
}
}
三、C++中的经典单例模式
以前在学习C++的时候,了解到过其中的智能指针的实现,就是采用单例模式实现的
1.写法一:因为java在堆中的new实例不需要程序员显示的来释放,C++的写法比上面的java中的写法多了一个静态变量用于计数引用的个数,但是这种写法创建的对象任然是指针,还是不方便。
#ifndef USERMANAGER_H
#define USERMANAGER_H
// 懒汉模式
class SmartPointer
{
private:
// 对象指针
static SmartPointer* m_Pointer= nullptr;
// 引用计数
static int m_handle_count = 0;
// 私有构造函数
UserManager() {
}
public:
static SmartPointer* getInstance(){
if(m_Pointer == nullptr){
m_Pointer = new SmartPointer();
}
m_handle_count++;
return m_Pointer;
}
~SmartPointer(){
if(m_handle_count > 0){
m_handle_count--;
}
if(m_Pointer != nullptr && m_handle_count == 0){
delete m_Pointer ;
m_Pointer = nullptr;
}
}
};
// 静态成员的初始化
SmartPointer* SmartPointer::m_Pointer = nullptr;
int SmartPointer::m_handle_count = 0;
// 饿汉模式
class SmartPointer
{
private:
static SmartPointer* m_Pointer = nullptr;
static int m_handle_count = 0;
SmartPointer() {
}
public:
static m_Pointer* getInstance(){
m_handle_count++;
return m_Pointer ;
}
~SmartPointer(){
if(m_handle_count > 0){
m_handle_count--;
}
if(m_Pointer != nullptr && m_handle_count == 0){
delete m_Pointer ;
m_Pointer = nullptr;
}
}
};
// 在类被加载的时候直接创建实例
SmartPointer* SmartPointer::m_Pointer = new SmartPointer();
int SmartPointer::m_handle_count = 0;
#endif // USERMANAGER_H
2.写法二、将指针封装成对象,然后去继承他实现,还是没有java使用方便
#ifndef SMARTPOINTER_H
#define SMARTPOINTER_H
#include "Pointer.h"
template <typename T>
class SmartPointer : public Pointer<T>
{
public:
SmartPointer(T* p = NULL) : Pointer<T>(p)
{
}
SmartPointer(const SmartPointer<T>& obj)
{
this->m_pointer = obj.m_pointer;
const_cast<SmartPointer<T>&>(obj).m_pointer = NULL;
}
SmartPointer<T>& operator =(const SmartPointer<T>& obj)
{
if(this != &obj)
{
T* p = this->m_pointer;
this->m_pointer = obj.m_pointer;
const_cast<SmartPointer<T>&>(obj).m_pointer = NULL;
delete p;
}
return *this;
}
~SmartPointer()
{
delete this->m_pointer;
}
};
#endif // SMARTPOINTER_H