第一次接觸Chaining Method概念是在使用jQuery時,jQuery中的Chaining Method
,讓代碼變得非常簡潔。Ruby中的Active Record
也是基于Chaining Method
設(shè)計的。基于Chaining Method
機制設(shè)計的API, 可以稱之為Chaining API
.
什么是Chaining Method
jQuery中
$("#person").slideDown('slow')
.addClass('grouped')
.css('margin-left', '11px');
如果不使用chaining:
var p = $('#person');
p.slideDown('slow');
p.addClass('grouped');
p.css('margin-left', '11px');
Active Record中
User.all.order(created_at: :desc)
如果不使用chain
users = User.all
ordered_users = users.order(created_at: :desc)
最簡單的Chaining Method實現(xiàn)
每次方法調(diào)用都返回當(dāng)前對象本身
class Person
def name(value)
@name = value
self
end
def age(value)
@age = value
self
end
def introduce
puts "Hello, my name is #{@name} and I am #{@age} years old."
end
end
person = Person.new
person.name("Peter").age(21).introduce
# => Hello, my name is Peter and I am 21 years old.
使用Chaining API處理數(shù)據(jù)
在Functional Programming世界中嚼摩,數(shù)據(jù)處理一般需要遵循data pipeline的原則,即:
- 數(shù)據(jù)從右向左流動(Functional Programming Way)
- 或者數(shù)據(jù)從左向右流動(OOP Way)
從右向左流動
sum(even(plus(1, [1,2,3,4,5])))
# => 12
從左向右流動
Processor.new([1,2,3,4,5]).plus(1).even().sum()
# => 6
OOP中的Chaining API的設(shè)計準則
- 使用數(shù)據(jù)構(gòu)建
Processor
對象,Processor
對象保存數(shù)據(jù)狀態(tài) - 調(diào)用
Processor
對象中的方法改變數(shù)據(jù)狀態(tài), 并且每個方法都返回Processor
本身 - 最后一次調(diào)用返回處理后的結(jié)果, 此處不在返回
Processor
對象本身 - 由于
Processor
中的每一次方法調(diào)用都會改變數(shù)據(jù)狀態(tài),所有不要重復(fù)使用Processor
對象矿瘦。Processor
對象用完立即銷毀
class DataProcessor
def initialize(datas)
@datas = datas
end
def plus(num)
@datas.map! { |n| n + num }
self
end
def even
@datas.select! { |n| n.even? }
self
end
def sum()
@datas.reduce(:+)
end
end
DataProcessor.new([1,2,3,4,5]).plus(1).even().sum()
#=> 12
總結(jié)
Chaining Method是一個非常優(yōu)雅的API設(shè)計方式枕面,采用Chaining Method方式設(shè)計API可以使代碼變得非常簡潔。在數(shù)據(jù)處理方面缚去,Chaining Method Way可以讓數(shù)據(jù)保持單項流動潮秘,在OOP中輕松實現(xiàn)Functional Programming中的Data Pipeline 思想。