Objective-C design mode ticket

Source: Internet
Author: User

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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.