IoC(Inversion of Control),也就是中文所说的控制反转,有时候也叫做DI(Dependency Injection),即依赖注射。在JAVA中,这样的容器不少,比如Spring。Ruby中也存在这样的容器,比如needle和Copland,这两个作品的作者都是Jamis Buck 。关于什么是DI/IoC,可以参看经典文章:Martin Fowler的 Inversion of Control and the Dependency Injection Pattern。
特点:
- 支持Type 2 (Setter) 和Type 3 (Constructor)的注射方式
- 为服务方法提供AOP的钩子实现拦截
- 分层的命名空间
- 生命周期管理(延迟初始化,单例模式等)
一个例子:
cacl.rb
module Calculator
class Adder
def compute( a, b )
a.to_f + b.to_f
end
end
class Subtractor
def compute( a, b )
a.to_f - b.to_f
end
end
class Multiplier
def compute( a, b )
a.to_f * b.to_f
end
end
class Divider
def compute( a, b )
a.to_f / b.to_f
end
end
class Sine
def compute( a )
Math.sin( a )
end
end
class Calculator
def initialize( operations )
@operations = operations
end
def method_missing( op, *args )
if @operations.has_key?(op)
@operations[op].compute( *args )
else
super
end
end
def respond_to?( op )
@operations.has_key?(op) or super
end
end
def register_services( registry )
registry.namespace! :calc do
namespace! :operations do
add { Adder.new }
subtract { Subtractor.new }
multiply { Multiplier.new }
divide { Divider.new }
sin { Sine.new }
end
calculator { Calculator.new( operations ) }
end
end
module_function :register_services
end
上面的类是一些实现类,可以被下面代码调用:
require 'needle'
require 'calc'
reg = Needle::Registry.new
Calculator.register_services( reg )
reg.calc.define! do
intercept( :calculator ).
with! { logging_interceptor }.
with_options( :exclude=>%w{divide multiply add} )
$add_count = 0
operations.intercept( :add ).
doing do |chain,ctx|
$add_count += 1
chain.process_next( ctx )
end
end
calc = reg.calc.calculator
puts "add(8,5): #{calc.add( 8, 5 )}"
puts "subtract(8,5): #{calc.subtract( 8, 5 )}"
puts "multiply(8,5): #{calc.multiply( 8, 5 )}"
puts "divide(8,5): #{calc.divide( 8, 5 )}"
puts "sin(pi/3): #{calc.sin( Math::PI/3 )}"
puts "add(1,-6): #{calc.add( 1, -6 )}"
puts
puts "'add' invoked #{$add_count} times"
参考资料:
1.Needle主页:http://needle.rubyforge.org
2.Dependency Injection in Ruby :http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc