文章目录
Java
静态变量—饿汉式
class Demo {
private static Demo uniqueInstance = new Demo();
private Demo() {
}
public static Demo getInstance() {
return uniqueInstance;
}
}
静态内部类—懒汉式
public class Demo {
private static class Singleton {
private static final Demo INSTANCE = new Demo();
}
private Demo() {
}
public static Demo getInstance() {
return Singleton.INSTANCE;
}
}
volatile + Double Check—懒汉式
方便初始化需要传参的场景
class Demo {
private volatile static Demo uniqueInstance;
private Demo() {
}
public static Demo getInstance() {
if (null == uniqueInstance) {
synchronized (Demo.class) {
if (null == uniqueInstance) {
uniqueInstance = new Demo();
}
}
}
return uniqueInstance;
}
}
Kotlin
对象声明—饿汉式
object Singleton {
val name = "Name"
fun fun1() {
println("fun1 $name")
}
}
伴生对象+延迟属性—懒汉式
class Singleton private constructor() {
companion object {
// lazy默认lazy(LazyThreadSafetyMode.SYNCHRONIZED)
val instance: Singleton by lazy {
Singleton()
}
}
}
C++
静态成员—饿汉式
Singleton.h
#ifndef KOTLINJAVACDEMO_SINGLETON_H
#define KOTLINJAVACDEMO_SINGLETON_H
#include <pthread.h>
class Singleton {
private:
static Singleton *singleton;
Singleton();
public:
static Singleton *getInstance();
};
#endif //KOTLINJAVACDEMO_SINGLETON_H
Singleton.cpp
#include "Singleton.h"
// 静态成员类内声明类外定义
Singleton *Singleton::singleton = new Singleton;
Singleton::Singleton() {
}
Singleton *Singleton::getInstance() {
return singleton;
}
Double Check—懒汉式
Singleton.h
#ifndef KOTLINJAVACDEMO_SINGLETON_H
#define KOTLINJAVACDEMO_SINGLETON_H
#include <pthread.h>
class Singleton {
private:
static pthread_mutex_t mutex;
static Singleton *instance;
Singleton();
public:
static Singleton *getInstance();
};
#endif //KOTLINJAVACDEMO_SINGLETON_H
Singleton.cpp
#include "Singleton.h"
// 必须定义全局变量,否则报错undefined reference to `Singleton::mutex'
pthread_mutex_t Singleton::mutex; // 如果mutex声明为局部变量,则需要pthread_mutex_init(&mutex, NULL)
// 必须定义全局指针,否则报错undefined reference to `Singleton::instance'
Singleton *Singleton::instance = NULL;
Singleton::Singleton() {
}
Singleton *Singleton::getInstance() {
if (instance == NULL) {
pthread_mutex_lock(&mutex);
if (instance == NULL) {
instance = new Singleton();
}
pthread_mutex_unlock(&mutex);
}
return instance;
}