Composite team design template

Does anyone have a good Ruby example of using Composite of Commands? This is a hybrid design pattern, which I already mentioned in the literature of various design patterns, which sounds quite powerful, but could not find interesting examples of use or code.

+3
source share
2 answers

Inspired by the general idea and examples of template templates in this blog post , here is a shot that he might look like:

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

And an example of using the application using a software installation program:

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
+3
source

I try to understand this pattern myself, and reflected on what can be modeled this way.

Composite - , . , , .

, ( Ruby Ruby Under the Microscope):

, . . , , .

, , , , , ..

run. , , .. true, true (, ..).

, , , , ..

, , , .. .

. , ..

, - . , . .

GUI

, , . , , , ..

Ruby , , ( ) , , . - : " ?"

((4 + 8) * 2)) + 9 4 + 8.

+1

All Articles