ruby way之高级OOP特性之二

本文介绍了Ruby语言中如何将代码块转换为对象,包括Proc、Method和UnboundMethod的使用方法。探讨了方法委托、默认参数检测及类级别的读写方法自动生成等高级主题。
1 把代码像对象一样存储

当你想要以对象的形式存储一块代码的时候,ruby给了你几种方法。下面我们会介绍Proc 对象, Method 对象和 UnboundMethod 对象.

内置的Proc 类包装ruby block到一个对象.Proc对象,像一个blocks,是一个闭包而且保存了它定义时的上下文:

myproc = Proc.new { |a| puts "Param is #{a}" }

myproc.call(99) # Param is 99


当一个方法接受一个&的参数,然后这个方法紧跟着一个block被调用的时候,Proc 对象就会自动被创建:

def take_block(x, &block)
puts block.class
x.times {|i| block[i, i*i] }
end

take_block(3) { |n,s| puts "#{n} squared is #{s}" }


这里要注意的是[]方法是call方法的别名。

如果你有一个Proc的对象,你可以把它传递给可以接收block的方法。只要在它前面加上&就行了.

myproc = proc { |n| print n, "... " }
(1..3).each(&myproc) # 1... 2... 3...


ruby也可以让你把一个方法插入到一个对象.这时要用到Object#method方法:

str = "cat"
meth = str.method(:length)

a = meth.call # 3 (length of "cat")

str << "erpillar"

b = meth.call # 11 (length of "caterpillar")

str = "dog"

# Note the next call! The variable str refers to a new object
# ("dog") now, but meth is still bound to the old object.

c = meth.call # 11 (length of "caterpillar")


最后一次调用请注意,由于str已指向另一个对象,因此这次调用,依然是老的对象.

你还能通过Module#instance_method 创建一个UnboundMethod 对象,它表示一个方法联系到一个类。你要调用unboundmethod对象,你必须首先绑定他到一个对象:

umeth = String.instance_method(:length)

m1 = umeth.bind("cat")
m1.call # 3

m2 = umeth.bind("caterpillar")
m2.call # 11


2 How Module Inclusion Works

具体的ruby中怎么处理include一个module,可以去看宝石书。

在一个被包含的模块里面的方法,都会被类里面所出现的方法所隐藏:

module MyMod
def meth
"from module"
end
end

class ParentClass
def meth
"from parent"
end
end

class ChildClass < ParentClass
include MyMod
def meth
"from child"
end
end

x = ChildClass.new
p x.meth #from child


这边可以看到MyMod里面的meth方法被ChildClass 中的所隐藏:

当我们在子类中调用super,会发生什么呢?

class ChildClass < ParentClass
include MyMod
def meth
"from child: super = " + super
end
end

x = ChildClass.new
p x.meth # from child: super = from module


这个例子展示了,其实模块才是子类真正的父类。那么让我们在模块的方法里面调用super:

module MyMod
def meth
"from module: super = " + super
end
end

# ParentClass is unchanged

class ChildClass < ParentClass
include MyMod
def meth
"from child: super = " + super
end
end

x = ChildClass.new
p x.meth # from child: super = from module: super = from parent


我们能在MyMod里面调用super方法,那是因为ParentClass类有meth方法,如果没有的话呢:

module MyMod
def meth
"from module: super = " + super
end
end

class Foo include MyMod
end

x = Foo.new
x.meth


他就会抛出一个NoMethodError 。

3 检测默认的参数

在2004年,Ian Macdonald 在邮件列表里面问了个问题:怎么样才能知道参数的值是默认的还是调用者付的.

Nobu Nakada给了一个最简单和最好的方法:

def meth(a, b=(flag=true; 345))
puts "b is #{b} and flag is #{flag.inspect}"
end

meth(123) # b is 345 and flag is true
meth(123,345) # b is 345 and flag is nil
meth(123,456) # b is 456 and flag is nil


4 Delegating 或者 Forwarding


ruby有两个库,它能够从接收者或者另外的对象来解决delegating或者forwarding 的方法调用.

SimpleDelegator用来委托给一个特定的对象,这个对象能够用__setobj__方法来改变:

DelegateClass 接受一个类作为参数:

require 'delegate'

class MyQueue < DelegateClass(Array)

def initialize(arg=[])
super(arg)
end

alias_method :enqueue, :push
alias_method :dequeue, :shift
end

mq = MyQueue.new

mq.enqueue(123)
mq.enqueue(234)

p mq.dequeue # 123
p mq.dequeue # 234


这里还有一种方法,就是从Delegator 继承,然后实现__getobj__ 方法,这也是SimpleDelegator 的实现方法。

如果你想要更多的控制,你可能想做到方法的委托,而不是类的委托,这时你可以使用forwardable 库。

require 'forwardable'

class MyQueue
extend Forwardable

def initialize(obj=[])
@queue = obj # delegate to this object
end

def_delegator :@queue, :push, :enqueue
def_delegator :@queue, :shift, :dequeue

def_delegators :@queue, :clear, :empty?, :length, :size, :<<

# Any additional stuff...
end


在这里要注意,def_delegator方法也就是把push方法委托到@queue对象,并且重命名为enqueue方法。

而def_delegators则是直接把他后面的参数都委托给@queue对象,并且方法名不变。

这个控制的比我们第一个例子,控制的细的多。

看例子:

q1 = MyQueue.new                    # use an array
q2 = MyQueue.new(my_array) # use one specific array
q3 = MyQueue.new(Queue.new) # use a Queue (thread.rb)
q4 = MyQueue.new(SizedQueue.new) # use a SizedQueue (thread.rb)


q3和 q4 都是线程安全的,因为他们委托给了一个线程安全的对象。

SingleForwardable 操作实例。当你需要把一个指定的对象委托给另一个对象时,就用得到了。

你可能会问有了委托,我们还要继承干嘛?这是一个错误的问题。比如ruby中没有多继承,你这时就能使用委托,来模拟实现。

5 自动定义类级别的读方法和写方法。

ruby中不能自动创建这个,可是我们可以模拟实现。

class MyClass

@alpha = 123 # Initialize @alpha

class << self
attr_reader :alpha # MyClass.alpha()
attr_writer :beta # MyClass.beta=()
attr_accessor :gamma # MyClass.gamma() and
end # MyClass.gamma=()

def MyClass.look
puts "#@alpha, #@beta, #@gamma"
end

#...
end


puts MyClass.alpha # 123
MyClass.beta = 456
MyClass.gamma = 789
puts MyClass.gamma # 789

MyClass.look # 123, 456, 789


这里要注意的是,这里我们打开了一个singleton class ,在一个singleton class 里面的实例变量,其实就是外面那层类的类实例变量.类实例变量不会被继承体系所共享,他是严格的per-class 。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值