• iOS


    前言

    • 单例对象能够被整个程序所操作。对于一个单例类,无论初始化单例对象多少次,也只能有一个单例对象存在,并且该对象是全局的,能够被整个系统访问到。

    单例类的创建

    1.1 单例类的创建 1

    • 单例类的创建

      	class SingleClass1 {
      		    
      		var text:String = "default"
      		    
      		class var sharedInstance: SingleClass1 {
      			struct Static {
      				static var onceToken: dispatch_once_t = 0
      				static var instance: SingleClass1? = nil
      			}
      			dispatch_once(&Static.onceToken) {
      				Static.instance = SingleClass1()
      			}
      			return Static.instance!
      		}
      	}
      
    • 单例类对象的调用

      	var single1:SingleClass1 = SingleClass1.sharedInstance
      	    
      	single1.text = "QQ"
      	    
      	var str = SingleClass1.sharedInstance.text
      	    
      	println(str)
      

    1.2 单例类的创建 2

    • 单例类的创建

      	class SingleClass2 {
      		    
      		var text:String = "default"
      		    
      		class var sharedInstance: SingleClass2 {
      			struct Static {
      				static let instance = SingleClass2()
      			}
      			return Static.instance
      		}
      	}
      
    • 单例类对象的调用

      	var single2:SingleClass2 = SingleClass2.sharedInstance
      	    
      	single2.text = "QQ"
      	    
      	var str = SingleClass2.sharedInstance.text
      	    
      	println(str)
      

    1.3 单例类的创建 3

    • 单例类的创建

      	private let sharedKraken = SingleClass3()
      	
      	class SingleClass3 {
      		    
      		var text:String = "default"
      		    
      		class var sharedInstance: SingleClass3 {
      			return sharedKraken
      		}
      	}
      
    • 单例类对象的调用

      	var single3:SingleClass3 = SingleClass3.sharedInstance
      	    
      	single3.text = "QQ"
      	    
      	var str = SingleClass3.sharedInstance.text
      	    
      	println(str)
      

    1.4 单例类的创建 4

    • 单例类的创建

      	class SingleClass4 {
      	    
      		var text:String = "default"
      		    
      		// This prevents others from using the default '()' initializer for this class.
      		static let sharedInstance = SingleClass4()
      		private init() {}
      	}
      
    • 单例类对象的调用

      	var single4:SingleClass4 = SingleClass4.sharedInstance
      	    
      	single4.text = "QQ"
      	    
      	var str = SingleClass4.sharedInstance.text
      	    
      	println(str)
      
  • 相关阅读:
    [LeetCode] Convert Sorted Array to Binary Search Tree
    [LeetCode] Diameter of Binary Tree
    [LeetCode] Student Attendance Record I
    [LeetCode] Reverse String II
    [LeetCode] Missing Number
    [LeetCode] Intersection of Two Arrays II
    [LeetCode] Base 7
    Ubuntu中firefox设置成中文
    Linux中的查找命令find
    Ubuntu14.04安装配置Chrome浏览器
  • 原文地址:https://www.cnblogs.com/QianChia/p/5777501.html
Copyright © 2020-2023  润新知