ruby - 命令设计模式的组合

标签 ruby oop design-patterns ooad

有人在 Ruby 中有使用命令组合的好例子吗?这是我在各种设计模式文献中看到的设计模式混合体,听起来很强大,但一直未能找到任何有趣的用例或代码。

最佳答案

受总体思路和the sample pattern implementations in this blog post启发,下面是它的外观:

class CompositeCommand
  def initialize(description, command, undo)
    @description=description; @command=command; @undo=undo
    @children = []
  end
  def add_child(child); @children << child; self; end
  def execute
    @command.call() if @command && @command.is_a?(Proc)
    @children.each {|child| child.execute}
  end
  def undo
    @children.reverse.each {|child| child.undo}
    @undo.call() if @undo && @undo.is_a?(Proc)
  end
end

以及使用软件安装程序应用程序的示例用法:

class CreateFiles < CompositeCommand
  def initialize(name)
    cmd = Proc.new { puts "OK: #{name} files created" }
    undo = Proc.new { puts "OK: #{name} files removed" }
    super("Creating #{name} Files", cmd, undo)
  end
end

class SoftwareInstaller
  def initialize; @commands=[]; end
  def add_command(cmd); @commands << cmd; self; end
  def install; @commands.each(&:execute); self; end
  def uninstall; @commands.reverse.each(&:undo); self end
end

installer = SoftwareInstaller.new
installer.add_command(
  CreateFiles.new('Binary').add_child(
    CreateFiles.new('Library')).add_child(
    CreateFiles.new('Executable')))
installer.add_command(
  CreateFiles.new('Settings').add_child(
    CreateFiles.new('Configuration')).add_child(
    CreateFiles.new('Preferences')).add_child(
    CreateFiles.new('Help')))
installer.install # => Runs all commands recursively
installer.uninstall

关于ruby - 命令设计模式的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10560892/

相关文章:

ruby-on-rails - Ruby on Rails - 从一个 Controller 更新多个模型

ruby-on-rails - 如何将 Heroku 应用程序从 MySql 切换到 PostgreSql

Java重写和重载在编译时抛出错误?

c# - 什么是领域驱动设计模式

ruby - 为什么我的正则表达式回溯在使用 Ruby 1.9 的 URL 上不起作用?

ruby-on-rails - 在 RSpec 测试中跳过 Rails http_basic_authenticate_with

matlab - 在 Matlab 中实现抽象属性的问题

php - PHP-检测另一个对象上的更改

java - 通过模式访问非公开方法

javascript - 模块化模式与原型(prototype) - Nodejs?