Swift單例模式

2021-09-06 10:07:19 字數 1048 閱讀 2912

**

大概分兩種:

1.繼承自 nsobject的

class singletonclass: nsobject

override func copy() -> any {

return self

// singletonclass.shared

override func mutablecopy() -> any {

return self // singletonclass.shared

// optional func reset() {

// reset all properties to default value

靜態屬性 shared 持有唯一的例項,對外公開。

過載 init() 方法,使其對外不可見,不可以在外部呼叫,防止在外部建立例項。

過載 copy()、mutablecopy() 方法,返回 self,防止在外部複製例項。這裡也可以返回 singletonclass.shared,效果是一樣的,因為只有乙個例項。只有 shared 能呼叫 copy()、mutablecopy() 方法,那麼 self 就是 shared。寫 self,**比較簡潔。

單例一旦建立,一直持有,不能手動銷毀,但可以重置資料。如果需要的話,可以新增乙個重置資料的方法 reset()。例如,當前使用者退出登入,需要把當前使用者例項的所有屬性重置為預設值,防止資料錯誤

2.不繼承自 nsobject

class singletonclass2 {

static let shared = singletonclass2()

// make sure the class has only one instance

// should not init outside

private init() {

// optional func reset() {

// reset all properties to default value

不繼承自 nsobject 的類沒有 copy()、mutablecopy() 方法,不需要過載。其他同上

Swift之單例模式

單例特點 單例的構造器必須為private 單例例項必須為執行緒安全的。單例優點 class caculaterectanglearea static func getrectanglearea x int,y int void caculaterectanglearea getrectanglea...

swift 建立單例模式

保證乙個類公有乙個例項,並提供乙個訪問它的全域性訪問點。1 使用場景 2 實現的重要三個步驟 swift語言不支援變數及方法的許可權,沒有辦法隱藏變數及方法,可以隨意直接建立乙個例項。單例的建立有很多寫法,swift支援只有struct支援靜態變數,class不支援靜態變數,所以很容易想到,在類的內...

Swift設計模式之單例 SINGLETON

保證乙個類公有乙個例項,並提供乙個訪問它的全域性訪問點。1 使用場景 2 實現的重要三個步驟 swift語言不支援變數及方法的許可權,沒有辦法隱藏變數及方法,可以隨意直接建立乙個例項。單例的建立有很多寫法,swift支援只有struct支援靜態變數,class不支援靜態變數,所以很容易想到,在類的內...