Http://unmi.cc/objective-c-dp-singleton
Objective-C design pattern Singleton
2011-08-25
-Unmi
As the simplest one in the design mode, the singleton mode is still used in many systems. There are always some instances that only need one of them from the slave, in addition, it is always easy to get it at any time, such as the application object and the environment image.
To ensure that the category person you design only has one initial instance, such as in Java/C ++/C #, we hope to ensure the following:
1. the constructor is hidden and private, so instances can only be obtained through the unified factory method, because new objects are always new objects.
2. The cloned object is still the original object.
3. The deserialized object is still the original unique object (it seems a bit difficult)
4. During normal running, the single instance is not released
5. The factory method is generally required to be atomic, and different instances are not returned.
6. Wait?
Not every point is taken into account, because not every use is so abnormal or does not exist in some use cases.
The objective-C here has a special feature in its language. It creates instances through alloc and cannot hide the constructor alloc, but we always have a solution, you can:
1. The factory method returns a unique instance
2. The instance constructed by calling alloc multiple times is the same as the factory method.
3. Let you release this instance, and the reference count will not be cleared to zero. Now let's take a look at the code implementation of the singleton mode in objective-C:
01020304050607080910111213141516171819202122232425262728293031323334353637383940 |