您的位置:首页 > 其它

设计模式之单例模式

2014-09-26 23:59 211 查看
  单例模式也称为单件模式,可能是所有模式中使用最广泛也是最简单的设计模。其目的是保证仅有一个类实例,
并提供一个访问它的全局访问点,该实例被所有程序模块共享。费话少说,重在意会,翠花上菜了:
  下面主要提两种常见的设计方法:普通方法与模板方法
  

1   /**
2     * @class Singleton
3     * @brief This is a  class for managing singleton \n
4     * objects allocated on the heap.
5     */
6     class Singleton
7     {
8     public:
9
10         /**
11          * Create a static object
12          * @return Singleton
13          */
14         static Singleton * Instance()
15         {
16             if(NULL == m_pInstance)
17                 m_pInstance = new Singleton();
18
19             return m_pInstance;
20         }
21
22         /**
23          * Destroy Singleton object
24          */
25         static void Unistance()
26         {
27             if(0 == m_pInstance)
28             {
29                 delete m_pInstance;
30                 m_pInstance = 0;
31             }
32         }
33
34     private:
35         Singleton() : m_pInstance(0) {}
36         Singleton(const Singleton&);
37         Singleton& operator=(const Singleton&);
38
39         static Singleton *m_pInstance;
40     };
41
42
43     /**
44     * @class Singleton
45     * @brief This is a template class for managing singleton objects allocated
46     * on the heap.
47     * For example
48     * class Test : public Singleton<Test>
49     * {
50     *        friend class Singleton<Test>;
51     * }
52     */
53     template <class T>
54     class Singleton
55     {
56     public:
57         /**
58          * Create a static object
59          * @return T*
60          */
61         static T* Instance()
62         {
63             if ( 0 == s_instance )
64             {
65                 s_instance = new T;
66             }
67
68             return s_instance;
69         }
70
71         /**
72          * Destroy Singleton object
73          */
74         static void Uninstance()
75         {
76             if ( 0 != s_instance )
77             {
78                 delete s_instance;
79                 s_instance = 0;
80             }
81         }
82
83     protected:
84         Singleton() {}
85         virtual ~Singleton() {}
86
87     private:
88         Singleton(const Singleton<T> &);
89         Singleton<T>& operator= (const Singleton<T> &);
90
91         static T* s_instance;
92     };
93
94     template <class T>
95     T* Singleton<T>::s_instance = 0;


  单例模式的优点:
    在内存中只有一个对象,节省内存空间
    避免频繁的创建销毁对象,可以提高性能
    避免对共享资源的多重占用
    可以全局访问
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: