Why Can Singleton classes be used as regular classes

佐手、 提交于 2019-12-06 13:27:42

问题


I was under the impression that the main reason for using singletons was to make sure that only one instance could be created in a program. I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.

In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.

What makes a singleton different than a regular class if it lets you create multiple instances?

// singleton class
class Car {
    static let sharedCar = Car()

    func run(){
        print("Running")
    }
}
// use
Car.sharedCar.run()

// other instances- I was expecting an error here
var jetta = Car()
jetta.run()

var cobalt = Car()
cobalt.run()

What am I missing here, can someone explain singletons?


回答1:


I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.

There is no language feature called "singleton", it is an idiomatic pattern. If you leave your implementation of singleton open for instantiations from outside, there is nothing the compiler can do about that.

In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.

You should add a private init to make sure there are no external instantiations:

class Car {
    static let sharedCar = Car()

    func run(){
        print("Running")
    }

    private init() {
    }
}

Now you are the only one who can instantiate your class. Users of Car class outside of your code are forced to rely on sharedCar instance that you create for them.



来源:https://stackoverflow.com/questions/38819314/why-can-singleton-classes-be-used-as-regular-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!