c ++ create schema - Singleton pattern (the Singleton)

1) intent:

Ensure that only one instance of a class, and it provides access to a global point

2) Structure:

 

 

   among them:

    Singleton provides a instance operation, this is the only instance of this kind of access to other customers.

  The only guarantee Examples include the following:

    1. The constructor and destructor are not open
    2. Publicly declare a static function as a single interface to access the class
    3. Example function declarations in a single static class pointer, and the lock protection good

3) Applicability:

  1. When only one instance of the class and the customer can access it from a well-known access point
  2. The only instance when this should be done by subclassing scalable, and customers do not have to change the code will be able to use the example of an extended

4) Example:

Here two example, a single embodiment, more than one case, a multiple embodiment is different class instances may be constructed according to different parameters, but these instances are unique.

  1. Singleton
 1 class  Singleton
 2 {
 3 private:
 4     Singleton() {}
 5     virtual ~Singleton() {}
 6 public:
 7     static Singleton* instance()
 8     {
 9         static Singleton* Instance;
10         if (Instance == NULL)
11         {
12             static CMutex Mutex;
13             Mutex.Lock();
14             if (Instance == NULL)
15             {
16                 Instance = new Singleton();
17             }
18             Mutex.Unlock();
19         }
20         return Instance;
21     }
22 };

  2. Multi cases

 1 std::map<int, Singleton*> Singleton::s_map;
 2 class  Singleton
 3 {
 4 private:
 5     Singleton(int num):m_num(num) {}
 6     virtual ~Singleton() {}
 7 public:
 8     static Singleton* instance(int num)
 9     {
10         for (std::map<int, Singleton*>::iterator it = s_map.begin();
11             it != s_map.end(); ++it)
12         {
13             if (it->first == num)
14             {
15                 return it->second;
16             }
17         }
18         static CMutex Mutex;
19         Mutex.Lock();
20         Singleton* Instance = new Singleton(num);
21         s_map.insert(std::map<int, Singleton*>::value_type(num, Instance));
22         Mutex.Unlock();
23         return Instance;
24     }
25 private:
26     static std::map<int, Singleton*> s_map;
27     int m_num;
28 };

Guess you like

Origin www.cnblogs.com/ho966/p/12229926.html