2

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 を記述しようとするのをやめるべきだ」という記事も読みました。

Rubyで等価性を実装する正しい方法は何ですか?

4

3 に答える 3

2

動的型付け言語へようこそ! どこにも宣言されていない関数を定義するだけで緊張したことでしょう。心配しないでください。これはとても簡単だ:

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

編集: 2つの異なるメソッド名を持つ必要を回避する別のオプションがあります:

class Base
  def process
    # ...
  end
end

class Child < Base
  def process
    # ...
    super   # calls the process method defined above in Base
    # ...
  end
end
于 2012-10-13T14:11:58.470 に答える
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

于 2012-10-13T14:14:14.920 に答える
0

パターンが

  • 家計の設定を行います(たとえば、リソースへの接続を作成します)
  • それを使って本当のことをする
  • 解体家事(フィ密着)

通常のメソッドに焼き付けられます:

# 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}"}
于 2012-10-13T21:16:13.383 に答える