Singleton VS静态(类)变量 [英] Singleton VS static(class) variables

查看:104
本文介绍了Singleton VS静态(类)变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift的最佳做法是什么?

What is the best practice in Swift?

选项1:

class SomeManager {

    static var sharedManager = SomeManager()

    var someVariable: String?

}

然后

let something = SomeManager.sharedManager().someVariable

选项2:

class SomeManager {

    static var someVariable: String?

}

然后

let something = SomeManager.someVariable


推荐答案

tl; dr



存储可变状态时的选项1(类或结构),因为您需要其他实例。

tl;dr

Option 1 (class or struct) when you store mutable state because you need other instances.

选项2(作用域全局变量)当你想存储静态变量时,因为它更快并且使用更少的内存。

Option 2 (scoped global variables) when you want to store static variables because it's faster and uses less memory.

全球状态通常被认为是坏事。这很难想到,导致问题,但有时是不可避免的。

Global state is generally considered a "bad thing". It's hard to think about, causes problems but is sometimes unavoidable.


  • 如果你想要多个 SomeManager 实例。

  • 单例可以是很好的默认实例,但可能存在需要单独行为(测试)的边缘情况。

  • 依赖注入.. 。 SomeManager 正在存储全局状态。是一个很重要的主题。

  • Create a class if you ever want to have multiple SomeManager instances.
  • A singleton can be good default instance but there may be edge cases where you want to have separate behavior (testing).
  • Dependency Injection... is big topic that is relevant if SomeManager is storing global state.

  • someVariable 为常量时,请务必使用。

  • 不需要额外存储空间var sharedManager = SomeManager();你只使用你实际需要的内存。

  • 稍快一点,因为你不需要将 sharedManager 加载到内存中然后访问它的成员 someVariable 。你直接访问 someVariable

  • Always use when the someVariable is a constant.
  • Does not require extra storage for static var sharedManager = SomeManager(); you use only the memory which you actually need.
  • Slightly faster because you do not need to load sharedManager into memory then access it's member someVariable. You straight up access someVariable.

在选项2中,您可以创建 SomeManager ,即使它没有做任何事情。你可以通过将 SomeManager 转换为一个没有任何案例的枚举来防止这种情况。

In Option 2 you can create SomeManager even though it doesn't do anything. You can prevent this by turning SomeManager into an enum with no cases.

enum SomeManager {
    static var someVariable: String?
}

您仍然可以这样做:

SomeManager.someVariable

但你可以'这样做

let manager = SomeManger()

这篇关于Singleton VS静态(类)变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆