【问题标题】:Constant vs. instance variable vs. instance method常量与实例变量与实例方法
【发布时间】:2014-10-18 04:53:11
【问题描述】:

我有一个基类 A 包含一个公共方法,该方法与 A 的后代提供的数组一起使用。该数组是:

  • 仅由基类A中定义的方法使用
  • 不变,但在某些特殊情况下会发生变化。

我应该如何处理这样定义的问题的对象设计?我仍然不确定自己在哪里存储该数组,无论是在常量、实例变量还是实例方法中。请告诉我如何做到这一点。

【问题讨论】:

  • 你使用什么语言?
  • 根据什么结果不同?

标签: ruby variables methods constants


【解决方案1】:

上次我对一个女新手很邪恶。这一次,我会努力表现得很好。

方法一,使用常量:

A = Class.new

class B < A
  FOO = [ :hello, :world ] # this is your array
end

# Access different constants defined in different descendants is tricky, like this:

class A
  def foo_user
    puts self.class.const_get :FOO
  end
end

B.new.foo_user #=> [ :hello, :world ]

# Note theat you can't do this:

class A
  def foo_user
    puts FOO # this would look for FOO in A mother class only
  end
end

 B.new.foo_user #=> error

方式二,使用属于 A 的子类的实例变量:

A = Class.new

class B < A
  @foo = [ "hello", "world" ]
end

# This way is more usable. I would go about it like this:

class A
  class << self
    attr_reader :foo     # defining a reader class method
  end

  def foo
    self.class.foo       # delegating foo calls on the instances to the class
  end

  def foo_user
    puts foo
  end
end

B.new.foo_user #=> [ :hello, :world ]

方式三,使用在后代上定义的实例方法:

A = Class.new

class B < A
  def foo
    [ "hello", "world" ]
  end
end

# This way is also usable.

class A
  def foo_user
    puts foo
  end
end

方式 2(属于后代类的实例变量)和方式 3(定义在后代类上的方法)之间的选择取决于值(数组)需要有多灵活。方式 2 最灵活,但方式 3 需要的代码更少。

【讨论】:

  • 谢谢你的好,我选择方式3。
  • 投了反对票,因为你不应该仅仅因为体面而被拍拍背。
猜你喜欢
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
  • 2013-03-24
  • 1970-01-01
相关资源
最近更新 更多