博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
029_siwft_两种单例模式
阅读量:370 次
发布时间:2019-03-04

本文共 787 字,大约阅读时间需要 2 分钟。

//单例模式 保证了只有一个实例的存在,这样有利于我们协调系统的整体行为,首先导入需要使用到的界面工具框架import UIKit//final 修饰符可以防止类被继承,还可以防止子类重写父类的属性、方法以及下标。该修饰符不能修饰结构体和枚举final class SigleClass:NSObject{    // 使用static 定义一个静态常量,静态常量在实例调用结束后不会消失,并且保留原值,即其内存空间不会释放,当下次调用实例时,仍然使用常量原有的值    static let shared = SigleClass()//    为了保持一个单例的唯一性。单例的构造器必须是private的,以防止其他对象也能创建出单例类的实例        private override init(){}        func say()  {        print("hello swift")    }                }SigleClass.shared.say()//使用静态变量的方式 实现第二个单例模式final class SecondStringletonClss: NSObject{    static var shared:SecondStringletonClss{        struct Static{            static let instance:SecondStringletonClss=SecondStringletonClss()        }        return Static.instance    }    private override init() {}        func say()  {        print("hello swift")    }}

 

转载地址:http://vtsr.baihongyu.com/

你可能感兴趣的文章