Ruby类变量是不是很糟糕?

ran*_*all 5 ruby singleton

当我实现"实例"/单例类型模式时,RubyMine通知使用类变量被认为是错误形式.

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

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
Run Code Online (Sandbox Code Playgroud)

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

小智 5

在Ruby类变量的问题是,当你从一个类继承,则新的类并没有获得自己的类变量的新副本,而是使用它继承自其超同一个.

例如:

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!
Run Code Online (Sandbox Code Playgroud)

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


Jam*_*rne -2

Ruby 类变量不好吗?就像任何主观问题一样,这取决于您的观点。关于全局变量的主题有大量文献,其中单例类本质上是一种形式。能够调用方法内部包含在调用方法中不可见的状态的事物往往会使理解事物变得困难并且维护成问题。

\n\n

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

\n\n

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

\n\n

将 -2.2.3 替换为您正在运行的 Ruby 版本。

\n\n

基本上:

\n\n

用法\xc2\xb6\xe2\x86\x91

\n\n
To use Singleton, include the module in your class.\n\nclass Klass\n   include Singleton\n   # ...\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n