fork download
  1. #include <iostream>
  2.  
  3.  
  4.  
  5. //T是任何继承此单例的类名
  6. template <class T>
  7. class Singleton
  8. {
  9.  
  10. public:
  11. //获取类的单例
  12. static inline T* getinstance();
  13. //释放类的单例
  14. void release();
  15. protected:
  16. //作为保护成员的构造函数
  17. Singleton(void){}
  18. //作为保护成员的析构函数
  19. ~Singleton(void){}
  20. //作为成员变量的静态单例
  21. static T* _instance;
  22. };
  23.  
  24.  
  25. //获取类的单例
  26. template <class T>
  27. inline T* Singleton<T>::getinstance()
  28. {
  29. if(!_instance)
  30. _instance=new T();
  31. return _instance;
  32. }
  33.  
  34. //释放类的单例
  35. template <class T>
  36. void Singleton<T>::release()
  37. {
  38. if(!_instance)
  39. return;
  40. delete _instance;
  41. _instance=0;
  42. }
  43.  
  44.  
  45. template <class T>
  46. T* Singleton<T>::_instance = 0;
  47.  
  48.  
  49. template <class Pro>
  50. class FactoryNew : public Singleton<FactoryNew<Pro> > //继承自单例类Singleton的工厂模式的模板
  51. {
  52. friend Singleton<FactoryNew<Pro> >;
  53. public:
  54.  
  55. Pro *create()
  56. {
  57. return new Pro();
  58. }
  59.  
  60. private:
  61. FactoryNew(){}
  62. ~FactoryNew(){}
  63. };
  64.  
  65.  
  66.  
  67. //产品C,由工厂FactoryNew生产
  68. class ProductC
  69. {
  70. public:
  71. ProductC(){}
  72. ~ProductC(){}
  73. void put(){std::cout<<"ProductC is here"<<std::endl;}
  74. };
  75.  
  76. //产品D,由工厂FactoryNew生产
  77. class ProductD
  78. {
  79. public:
  80. ProductD(){}
  81. ~ProductD(){}
  82. void put(){std::cout<<"productD is here"<<std::endl;}
  83. };
  84.  
  85. int main()
  86. {
  87.  
  88.  
  89. ProductC *proC = FactoryNew<ProductC>::getinstance()->create();
  90. proC->put();
  91. delete proC;
  92. FactoryNew<ProductC>::getinstance()->release();
  93.  
  94. ProductD *proD = FactoryNew<ProductD>::getinstance()->create();
  95. proD->put();
  96. delete proD;
  97. FactoryNew<ProductD>::getinstance()->release();
  98. return 0;
  99. }
  100.  
  101.  
  102.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
ProductC is here
productD is here