<< 前 ホーム 次 >>

bakaid: 20071226

下書き。

class Service
  def new_instance
    return self.class.new
  end

  def accept_server(name, server)
  end
end

class Dependency
  def initialize(proto, dependents)
    @proto = proto
    @dependents = dependents
  end
  attr_reader :proto, :dependents
end

class Container
  def initialize
    @dependencies = {}
    @services = {}
  end

  def register(name, proto, dependents)
    @dependencies[name] = Dependency.new(proto, dependents)
  end

  def assemble
    new_instances
    connect
  end

  def new_instances
    @dependencies.each do |name, dep|
      @services[name] = dep.proto.new_instance
    end
  end

  def connect
    @dependencies.each do |name, dep|
      client = @services[name]
      dep.dependents.each do |dep_name|
        server = @services[dep_name]
        client.accept_server(dep_name, server)
      end
    end
  end

  def get_service(name)
    return @services[name]
  end
end

class Openfilename < Service
  def open(path)
    path << 'Openfilename'
    return true
  end
end

class Filer < Service
  def initialize
    @openfilename = nil
  end

  def accept_server(name, server)
    name == 'Openfilename' and @openfilename = server
  end

  def open(path)
    return @openfilename.open(path)
  end
end

class AppModel < Service
  def initialize
    @ctrl = nil
    @filer = nil
  end

  def accept_server(name, server)
    case name
    when 'AppControl'
      @ctrl = server
    when 'Filer'
      @filer = server
    end
  end

  def open
    path = ''
    if @filer.open(path)
      puts(path)
    else
      puts('open failed')
    end
  end
end

class AppControl < Service
  def initialize
    @model = nil
  end

  def accept_server(name, server)
    name == 'AppModel' and @model = server
  end

  def dispatch(event)
    event == 'Open' and @model.open
  end
end

container = Container.new
container.register('Openfilename', Openfilename.new, [])
container.register('Filer', Filer.new, ['Openfilename'])
container.register('AppModel', AppModel.new, ['AppControl', 'Filer'])
container.register('AppControl', AppControl.new, ['AppModel'])
container.assemble
ctrl = container.get_service('AppControl')
ctrl.dispatch('Open')

本家Permlink

<< 前 ホーム 次 >>


Copyright © 1905 tko at jitu.org

バカが征く on Rails