在Java中,我习惯于编写一个抽象类来完成一些设置工作,然后像这样委托给具体的类:
public abstract class Base {
public void process() {
// do some setup
...
// then call the concrete class
doRealProcessing();
}
protected abstract void doRealProcessing();
}
public class Child extends Base {
@Override
protected void doRealProcessing() {
// do the real processing
}
}
我很难在Ruby中执行此操作,因为我没有抽象类或方法。我也读到你不应该在Ruby中需要抽象类或方法,我应该停止尝试在Ruby中编写Java。
我很乐意 - 实现这种类型构造的正确方法是什么?
答案 0 :(得分:1)
欢迎使用动态类型语言!你可能很担心只定义一些未在任何地方声明的函数。别担心。这很容易:
class Base
def process
# ...
real_processing
end
def real_processing # This method is optional!
raise "real_processing not implemented in #{self.class.name}"
end
end
class Child < Base
def real_processing
# ...
end
end
b = Child.new
b.process
编辑:这是您的另一个选项,它可以避免需要两个不同的方法名称:
class Base
def process
# ...
end
end
class Child < Base
def process
# ...
super # calls the process method defined above in Base
# ...
end
end
答案 1 :(得分:0)
以下是如何在Ruby中执行模板模式:
class Template
def template_method
perform_step1
perform_step2
#do some extra work
end
def perform_step1
raise "must be implemented by a class"
end
def perform_step2
raise "must be implemented by a class"
end
end
class Implementation < Template
def perform_step1
#implementation goes here
end
def perform_step2
#implementation goes here
end
end
http://andymaleh.blogspot.com/2008/04/template-method-design-pattern-in-ruby.html
答案 2 :(得分:0)
对于这个用例,你在Ruby中看不到这个,因为模式
融入普通方法:
# pseudocode:
def a_method(an_argument)
# do some setup with an_argument
yield(a_result)
# do some teardown
end
# use like:
a_method(the_argument){|the_result| puts "real processing with #{the_result}"}