Ruby类变量是不是很糟糕?

当我实现“实例”/单例类型模式时,RubyMine通知使用类变量被认为是错误forms。

我遇到的唯一信息是使用类变量可以使inheritance有点松散。 以下代码会给我带来什么问题还有其他原因吗?

class Settings private_class_method :new attr_accessor :prop1 attr_accessor :prop2 @@instance = nil def Settings.instance_of @@instance = new unless @@instance @@instance end def initialize @prop2 = "random" end end 

此外,有没有更好的方法,从Ruby方面来说,实现相同的目标,以确保只有一个实例?

Ruby中类变量的问题在于,当您从类inheritance时,新类不会获取其自己的类变量的新副本,而是使用从其超类inheritance的相同类。

例如:

 class Car @@default_max_speed = 100 def self.default_max_speed @@default_max_speed end end class SuperCar < Car @@default_max_speed = 200 # and all cars in the world become turbo-charged end SuperCar.default_max_speed # returns 200, makes sense! Car.default_max_speed # returns 200, oops! 

建议的做法是使用类实例变量(请记住,类只是Ruby中类Class的对象)。 我强烈推荐阅读Russ Olsen的第14章Eloquent Ruby ,它详细介绍了这个主题。

Ruby类变量是不是很糟糕? 像任何主观问题一样,这取决于你的观点。 关于全局变量主题的广泛文献中,单例类本质上是一种forms。 能够在调用中隐藏的方法中调用包含状态的东西往往会使理解困难并且维护有问题。

对于Ruby-1.9.3及更高版本,请参阅文档以获得更好的方法:

http://ruby-doc.org/stdlib-2.2.3/libdoc/singleton/rdoc/Singleton.html

用你正在运行的任何Ruby版本替换-2.2.3。

基本上:

用法↑

 To use Singleton, include the module in your class. class Klass include Singleton # ... end 

单身人士不好吗? 好吧,自2004年以来,我一直在使用ruby,我只记得有一次我甚至考虑使用单身人士。 我不记得细节,所以我推断我实际上并没有这样做。 对单身人士的需求通常表明您正在解决的问题需要以更清晰的方式重新制定。