由于使用场景的不同,单例模式的写法也有所区别。
目前接触到的,大多数都是多线程,大量数据处理,还要考虑灵活性,对原有类结构改动最小等因素,所以写法更是多种多样。
QT个人较常用的一种写法:(两个文件:分为.h文件和.cpp文件)
1 class LocalBusiness : public QObject 2 { 3 Q_OBJECT 4 5 private: 6 QString _myName; 7 explicit LocalBusiness(QObject *parent = nullptr); 8 static LocalBusiness* _instance; 9 public: 10 static LocalBusiness* Instance() 11 { 12 static QMutex mutex; 13 if (!_instance) { 14 QMutexLocker locker(&mutex); 15 if (!_instance) { 16 _instance = new LocalBusiness; 17 } 18 } 19 return _instance; 20 } 21 public: 22 void SayHello(); 23 24 };
1 LocalBusiness* LocalBusiness::_instance = nullptr; 2 3 LocalBusiness::LocalBusiness(QObject *parent) : QObject(parent) 4 { 5 _myName="LocalBusiness"; 6 } 7 8 void LocalBusiness::SayHello() 9 { 10 qDebug() << "hello,"+_myName; 11 }
具体调用
1 LocalBusiness::Instance()->SayHello();
C#个人较常用的写法:(一个文件:.cs文件)
1 public class LocalBusiness 2 { 3 private readonly string _myName = string.Empty; 4 private static LocalBusiness _instance = null; 5 private static readonly object _locker = new object(); 6 7 private LocalBusiness() 8 { 9 _myName = "LocalBusiness"; 10 } 11 12 public static LocalBusiness Instance 13 { 14 get 15 { 16 if (_instance == null) 17 { 18 lock (_locker) 19 { 20 if (_instance == null) 21 { 22 _instance = new LocalBusiness(); 23 } 24 } 25 } 26 return _instance; 27 } 28 } 29 30 public void SayHello() 31 { 32 Console.WriteLine("hello,"+ _myName); 33 } 34 }
具体调用
1 LocalBusiness.Instance.SayHello();
如果有帮助,欢迎素质三连~