iOS

【设计模式】单例模式

2015-12-14  本文已影响149人  刘大帅

学习文章

原理图

单例模式原理图.png

说明

源码

严格的单例模式不应该被继承,不应该被复制,不应该被new等等,只应该独此一家.

Singleton.swift

import Foundation

enum SingletonError : ErrorType {

    case CannotBeInherited
}

class Singleton {
    
    /* --不能被子类调用-- */
    static func sharedInstance() throws -> Singleton {
        
        guard self == Singleton.self else {
        
            print("--------Can't be inherited !--------")
            throw SingletonError.CannotBeInherited
        }
        
        struct Static {

            static let sharedInstance = Singleton()
        }
        
        return Static.sharedInstance
    }
    
    private init()  {

    }
}
  

下载源码

下载地址

上一篇 下一篇

猜你喜欢

热点阅读