The method of creating a single embodiment of the Objective-C in step

Transfer: single embodiment of the Objective-C method created in step

Singleton (Singleton), is a popular software design patterns, class singleton object must ensure that only one instance of existence, in many cases the entire system only need to have a global object, this will help us to coordinate the behavior of the system. As a server program, the server configuration information is stored in a file, the configuration data is read by a unified singleton object, and other objects in the process of re-acquiring service configuration information through the singleton object, such It simplifies the configuration management in complex environments.

Ideas to achieve Singleton pattern is: a class can return an object instance (always the same) and a method to get the instance (must be a static method, commonly used getInstance this name), when we call this method, if the class examples of holding is not empty, returns this instance, if the class is kept empty, it creates an instance of the class, and gives examples of instances of the class remain, thereby limiting the user only through the static methods provided by this class been the only instance of the class.

Singleton must be carefully used in multi-threaded applications, the only instance when not yet created, if there are two threads creation method calls, they do not simultaneously detect the presence of a unique instance, to simultaneously create an instance of each, so two examples have been constructed, thus violating the singleton pattern in Example unique principle. The solution to this problem is to provide a mutex (although this will reduce the efficiency) to mark whether the class has been instantiated variables.

Create a single embodiment of the method the following steps:

1. your singleton instance of a static class declaration, and initializes its value is nil;

2. In the process of acquiring instance, only static instance is nil when generating an instance of your class, and this instance is often referred to examples of shared;

3. Rewrite allocWithZone method for determining: We can not create an instance of the class to use other methods limit the user to get an instance of this class by the method of acquiring instance. Therefore, we return directly in the shared class instance allocWithZone process;

4. Examples of the basic protocol method copyWithZone:, release, retain, retainCount and autorelease, to ensure that a single embodiment having a correct state. The last four methods is user memory management code, the code does not apply to garbage collection.

Reproduced in: https: //www.cnblogs.com/hxxy2003/archive/2013/04/16/3023662.html

Guess you like

Origin blog.csdn.net/weixin_33816946/article/details/93892252