单例模式比对

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值