奇异递归模板模式
Curiously Recurring Template Pattern,CRTP
最近发现一个很优雅的写法,CRTP,利用了模版和继承的特性,实现了一种奇观的“自我认知”,可以省去写很多重复代码
C#实现一个单例
定义
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Singleton<T> : MonoBehaviour where T : Component { protected static T _instance; public static bool HasInstance => _instance != null; public static T Instance { get { if (_instance == null) { _instance = FindObjectOfType<T> (); if (_instance == null) { GameObject obj = new GameObject (); obj.name = typeof(T).Name + "_AutoCreated"; _instance = obj.AddComponent<T> (); } } return _instance; } } protected virtual void Awake () { InitializeSingleton(); } protected virtual void InitializeSingleton() { if (!Application.isPlaying) { return; } _instance = this as T; } }
|
使用
public class GlobalTableManager : Singleton<GlobalTableManager> {...}
|
C++实现一个单例
定义
#include <iostream>
template <typename T> class Singleton { protected: static T* instance;
Singleton() {}
public: static T* getInstance() { if (!instance) { instance = new T(); } return instance; }
static void destroyInstance() { delete instance; instance = nullptr; } };
template <typename T> T* Singleton<T>::instance = nullptr;
|
使用
class MySingleton : public Singleton<MySingleton> { public: void print() { std::cout << "Hello" << std::endl; } };
int main() { MySingleton::getInstance()->print(); return 0; }
|