我仍然很困惑什么时候最好从另一个类继承,或者当你最好返回另一个类的新实例时,最好的方法是什么。目的是获得一种可链接的方式来创建各种类型的按钮。这是一些示例代码:
class Button
def initialize link
@link = link
end
def color(color)
@color = color
return self
end
end
# Now I'm wondering what is the best approach to do something like:
class RedButton < Button
def initialize link
super
color('red')
end
end
# or
class Redbutton
def initialize link
return Button.new(link).color('red')
end
end
或者这基本上是一样的?
类是用于创建对象的蓝图。实例化创建类的新实例(新对象)。继承创建一个新的类,即一个新的蓝图。它们是不同的概念。
第二个例子并不像你想象的那样工作。该initialize
方法是在类的构造函数。new
当创建新实例时,它由类方法调用。它不能返回一个值(好吧,它总是返回一个值,但它被忽略了)。
在Redbutton
第二个例子类是新的空类,与任何不相关Button
的类。它的构造函数创建Button
该类的一个新实例并返回它,但返回的对象没有存储在任何地方,它在下一个垃圾收集周期被解释器销毁。
第二个Redbutton
类是相同的:
class Redbutton
def initialize link
end
end
类的第一个实现Redbutton
(扩展的那个Button
)在语义上是正确的。它创建了一个在创建过程中将Button
其@color
属性设置为的对象'red'
。
更新(对评论中发布的问题的回答)
最好的方法取决于很多因素。您会在处理项目时发现它。如果RoundButton
并SquareButton
提供与基类 ( )不同的功能,Button
那么为它们创建单独的类是有意义的。如果您还需要RedRoundButton
(扩展什么类?RedButton
或RoundButton
?),您会遇到挑战,并且您会发现很多时候继承不是解决方案。
但是,如果RedButton
和之间的唯一区别Button
是一个字段(或多个字段)的值,那么您最好在类Button
(或工厂类)中创建一个工厂方法,该方法知道如何创建和初始化红色按钮、圆形按钮、红色按钮圆形按钮等,例如:
class Button
def initialize link
@link = link
end
def color(color)
@color = color
self
end
def shape(shape)
@shape = shape
self
end
def self.create(type, link)
case type
when 'RedButton'
self.new(link).color('red')
when 'RoundButton'
self.new(link).shape('round')
when 'RedRoundButton'
self.new(link).color('red').shape('round')
else
raise 'Unknown type'
end
end
end
x = Button.create('RedButton', 4)
y = Button.create('RedRoundButton', 6)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句