Four ways Swift implements a single case

Source: Internet
Author: User


Single-Case mode

The singleton pattern is the simplest of the design patterns, and even some schema masters do not call it a pattern, calling it an implementation technique, because the design pattern emphasizes the abstraction of the relationship between objects, whereas singleton patterns have only one object.

When you need only one instance to use singleton, such as UIApplication.sharedApplication() , Windows Task Manager, the Recycle Bin can only exist at the same time.

Let's look at several implementations in Swift:

1.

import Foundationclass SingleOne { //单例 static let shareSingleOne = SingleOne()}

A word to be done, static commonsense. All the places used are the same

2.

ImportFoundationclass singletwo {//single case class func sharesingletwo ()->singletwo{struct singleton{static var oncetoken:dispatch_once_t = 0  Static var single:singletwo?} dispatch_once (&singleton.oncetoken,{singleton.single=sharesingletwo ()}) return singleton.single!}}         

Use Dispatch_once to ensure that the code is executed only once

3.

import Foundation//全局的常量let single = SingleThree()class SingleThree { class var sharedInstance : SingleThree { return single }}

4.

import Foundationclass SingleFour { static var sharedInstance : SingleFour { struct Static { static let instance : SingleFour = SingleFour() } return Static.instance }}

Defining static constants within a method



Paper/Big stone cloth (Jane book author)
Original link: http://www.jianshu.com/p/230cc900948c
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Four ways Swift implements a single case

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.