基于结构和基于类的单例有什么区别? [英] What's the difference between Struct based and Class based singletons?
问题描述
这两种方法是否相同,或者是否存在需要注意的主要差异/陷阱:
class MyClassSingleton {静态 let sharedInstance = MyClassSingleton()私有初始化(){}func helloClass() { print("来自单例类的你好") }}struct MyStructSingleton {静态 let sharedInstance = MyStructSingleton()私有初始化(){}func helloStruct() { print("来自结构单例的你好") }}
主要区别在于基于类的可变单例有效,而基于结构的可变单例"无效.除非你想让你的单例不可变(这种情况很少见),否则你应该坚持基于类的.
这是一个基于可变结构的单例"如何不起作用的说明.考虑向两个单例添加一个可变成员 state
,如下所示:
class MyClassSingleton {静态 let sharedInstance = MyClassSingleton()私有初始化(){}无功状态 = 5func helloClass() { print("来自单例类的你好:\(state)") }}struct MyStructSingleton {静态 let sharedInstance = MyStructSingleton()私有初始化(){}无功状态 = 5func helloStruct() { print("来自struct Singleton的hello: \(state)") }}
我将 state
变成了一个 var
,但我可以将它作为只读属性和变异方法公开;最重要的是,这两种类型现在都是可变的.
如果我这样做
let csi = MyClassSingleton.sharedInstancecsi.state = 42MyClassSingleton.sharedInstance.helloClass()
42 被打印出来,因为 csi
正在引用共享实例.
但是,当我用基于结构的单例做同样的事情时
var ssi = MyStructSingleton.sharedInstancessi.state = 42MyStructSingleton.sharedInstance.helloStruct()
5 被打印出来,因为 ssi
是 sharedInstance
的副本,当然,这表明我们的单例实际上不是单例.>
Are the two approaches the same or are there major differences/pitfalls to be aware of:
class MyClassSingleton {
static let sharedInstance = MyClassSingleton()
private init(){}
func helloClass() { print("hello from class Singleton") }
}
struct MyStructSingleton {
static let sharedInstance = MyStructSingleton()
private init() {}
func helloStruct() { print("hello from struct Singleton") }
}
The main difference is that class-based mutable singleton works, while struct-based mutable "singleton" doesn't. Unless you want to make your singleton immutable (which is rare) you should stick to the class-based one.
Here is an illustration of how mutable struct-based "singleton" does not work. Consider adding a mutable member state
to both singletons, like this:
class MyClassSingleton {
static let sharedInstance = MyClassSingleton()
private init(){}
var state = 5
func helloClass() { print("hello from class Singleton: \(state)") }
}
struct MyStructSingleton {
static let sharedInstance = MyStructSingleton()
private init() {}
var state = 5
func helloStruct() { print("hello from struct Singleton: \(state)") }
}
I made state
a var
, but I could expose it as a read-only property plus a mutating method; the essential thing is that both types are now mutable.
If I do this
let csi = MyClassSingleton.sharedInstance
csi.state = 42
MyClassSingleton.sharedInstance.helloClass()
42 gets printed, because csi
is referencing the shared instance.
However, when I do the same thing with struct-based singleton
var ssi = MyStructSingleton.sharedInstance
ssi.state = 42
MyStructSingleton.sharedInstance.helloStruct()
5 gets printed instead, because ssi
is a copy of the sharedInstance
, which is, of course, an indication that our singleton is not actually a singleton.
这篇关于基于结构和基于类的单例有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!