我有一个基类A,它包含一个公共方法,它使用A.的后代提供的数组,数组是:
A中定义的方法使用。我应该如何处理这样定义的问题的对象设计?无论是在常量、实例变量还是实例方法中,我仍然不确定将该数组存储在何处。请教我怎么做。
发布于 2014-08-25 06:30:04
上一次我对一个女新手来说是邪恶的。这一次,我会尽量表现得好点。
方法一,使用常量:
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所需代码较少。
https://stackoverflow.com/questions/25479134
复制相似问题