クラスのメソッド呼び出しとその具体的な振る舞いを分離することを目的とする。
class AttackSordCommand def do attacker = AttackerSord.new attacker.attack end end
class DefenderShieldCommand def do defender = DeffenderShield .new defender.defence end end
class Yusha def initialize(attack_command, defence_command) @attack_command = attack_command @defence_command = defence_command end def kogeki @attack_command.do end def bogyo @defence_command.do end end
勇者クラスは攻撃した際にどんなことが起こるのか知りません。
その具体的なことはAttackCommandが知っています。
防御した際も同様です。
剣で攻撃だったのが槍で攻撃に代わっても勇者クラスは変更しなくてすみます。
今まで
yusha = Yusha.new(AttackSordCommand.new, DefenderShieldCommand)
だったのが
槍コマンドクラスが追加されて
class AttackSpearCommand def do attacker = AttackerSpear.new attacker.attack end end
以下のように勇者クラスの生成方法が変わるだけです。
yusha = Yusha.new(AttackSpearCommand.new, DefenderShieldCommand)