函數式編程-->closure

所謂閉包,其實是一種特殊的函數,它在暗地裏綁定了函數內部引用的全部變量。換句話說,這種函數(或方法)把它引用的全部東西都放在一個上下文裏「包」起來了。閉包

Groovy語言中閉包綁定的簡單示例函數

class Employee{

      def name,salary
}

def paidMore(amount){
return {Employee e -> e.salary > amount} }
isHighPaid
= paidMore(100000)

執行閉包spa

def Smithers = new Employee(name:"Fred", salary:120000)
def Homer = new Employee(name:"Homer", salary:80000)
println isHighPaid(Smithers)
println isHighPaid(Homer)
// true, false

綁定另外一個閉包code

isHigherPaid = paidMore(200000)
println isHigherPaid(Smithers)
println isHigherPaid(Homer)
def Burns = new Employee(name:"Monty", salary:1000000)
println isHigherPaid(Burns)
// false, false, true

閉包的原理blog

def Closure makeCounter(){
    
   def local_variable
= 0 return { return local_variable += 1 //[1] } c1 = makeCounter() //[2] c1()         //[3] c1() c1() c2 = makeCounter() //[4] println "C1 = ${c1(),C2 = ${c2()}" //output: C1 = 4, C2 = 1 //[5]

[1]函數的返回值是一個代碼塊,而不是一個值。it

[2]c1如今指向代碼塊的一個實例。class

[3]調用c1將遞增其內部變量,若是這個時候輸出,其結果會是1。變量

[4]c2如今指向makeCounter()的一個全新實例,與其餘實例沒有關聯。原理

[5]每一個實例的內部狀態都是獨立的,各自擁有一份local_variable。引用

相關文章
相關標籤/搜索