简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
文章目录
- 1.前言
- 2.Android使用模板类单例模式例子
- <1>.实例化
- <2>.android源码使用例子
- 3.实现模板类单例模式
1.前言
本篇目的:通过模板实现单例模式,帮助读者理解模板和单例模式。
2.Android使用模板类单例模式例子
<1>.实例化
frameworks/av/media/libaaudio/src/binding/AAudioBinderClient.cpp
ANDROID_SINGLETON_STATIC_INSTANCE(AAudioBinderClient);
AAudioBinderClient::AAudioBinderClient() : AAudioServiceInterface(), Singleton<AAudioBinderClient>() {
gKeepBinderClient = this; // so this singleton won't get deleted
mAAudioClient = new AAudioClient(this);
ALOGV("%s - this = %p, created mAAudioClient = %p", __func__, this, mAAudioClient.get());
}
AAudioBinderClient继承自AAudioServiceInterface和Singleton类。
而Singleton为模板类单例模式。
<2>.android源码使用例子
frameworks/av/media/libaaudio/src/core/AudioStreamBuilder.cpp
stream = new AudioStreamInternalCapture(AAudioBinderClient::getInstance(), false);
调用:AAudioBinderClient::getInstance()获取AAudioBinderClient类实例化对象。
3.实现模板类单例模式
#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename TYPE>
class Singleton{
public:
static TYPE& getInstance() {
TYPE* instance = sInstance;
if (instance == nullptr) {
instance = new TYPE();
sInstance = instance;
}
return *instance;
}
protected:
Singleton() {
printf("%s(), line = %d\n",__FUNCTION__,__LINE__);
}
~Singleton() {
printf("%s(), line = %d\n",__FUNCTION__,__LINE__);
}
private:
Singleton(const Singleton&);
Singleton& operator = (const Singleton&);
static TYPE* sInstance;
};
#define SINGLETON_STATIC_INSTANCE(TYPE) \
template<> TYPE* Singleton< TYPE >::sInstance(nullptr); \
template class Singleton< TYPE >;
class/*struct*/ SingleTest : public Singleton<SingleTest> {
public:
SingleTest(){
printf("%s(), line = %d\n",__FUNCTION__,__LINE__);
}
~SingleTest(){
printf("%s(), line = %d\n",__FUNCTION__,__LINE__);
}
unsigned int contents;
};
SINGLETON_STATIC_INSTANCE(SingleTest);
int main(){
//1.单例模式
SingleTest *s1 = &SingleTest::getInstance();
SingleTest *s2 = &SingleTest::getInstance();
if (s1 == s2) {
cout << "s1 == s2" << endl;
} else {
cout << "s1 != s2" << endl;
}
s1->contents = 100;
printf("s1->contents = %d\n",s1->contents);
//销毁一次,因为只有一个实例
delete s1;
//2.一般构造
SingleTest *s3 = new SingleTest();
s3->contents = 200;
printf("s3->contents = %d\n",s3->contents);
delete s3;
}