1. 閉包代表(定義)了一段代碼(操作):光看這一句,其實(shí)方法也能實(shí)現(xiàn)相同的功能呀。
2. 閉包可以作為方法的參數(shù):這才是閉包的特殊之處和真正意義。
下面演示一個(gè)只有閉包能做,方法做不到的例子。
方法的作用是提煉共性,再代之以不同的參數(shù)。即對(duì)不同的“數(shù)據(jù)”進(jìn)行相同的“操作”。從3個(gè)loop可以看出:
????Comm1:相同的數(shù)據(jù)
????Comm2:相同的for循環(huán)
????Diff1:循環(huán)體內(nèi)執(zhí)行的操作不同
Comm1很好搞定,參數(shù)aa就是提煉出的共性
Comm2看似是共性,卻很難提煉,因?yàn)閒or循環(huán)和循環(huán)體內(nèi)的操作實(shí)際是一個(gè)整體;Comm2被Diff1糾纏,3個(gè)loop是完全不同的3組操作,無(wú)法提煉。
比如,如果現(xiàn)在想要按照奇數(shù)循環(huán),只能依次改動(dòng)三個(gè)循環(huán)。?
int
[]?aa?
=
?[
1
,?
2
,?
3
,?
4
,?
5
,?
6
]
//
?loop1
for
?(
int
?i?
=
?
0
;?i?
<
?aa.length;?i
++
)?{ ????println?aa[i] }
//
?loop2
for
?(
int
?i?
=
?
0
;?i?
<
?aa.length;?i
++
)?{ ????print?aa[i] }
//
?loop3
for
?(
int
?i?
=
?
0
;?i?
<
?aa.length;?i
++
)?{ ????print?aa[i]?
+
?
'
?
'
}
|
????????
//
?loop1
for
?(
int
?i?
=
?
0
;?i?
<
?aa.length;?i?
+=
?
2
)?{ ????println?aa[i] }
//
?loop2
for
?(
int
?i?
=
?
0
;?i?
<
?aa.length;?i?
+=
?
2
)?{ ????print?aa[i] }
//
?loop3
for
?(
int
?i?
=
?
0
;?i?
<
?aa.length;?i?
+=
?
2
)?{ ????print?aa[i]?
+
?
'
?
'
}
|
下面我們看看閉包的強(qiáng)大之處,Comm1和Comm2都被很好的封裝在了loop方法里;
Diff1則作為參數(shù)(閉包)傳入loop方法。
static?void?main(String[]?a)?{
????int[]?aa?=?[1,?2,?3,?4,?5,?6]
????loop(aa)?{?println?it }
??? loop(aa)?{?print?it?}???
??? loop(aa)?{?print?it?+?'?'?}
}
|
如果我們想要改變循環(huán)的方式,只需要改一處
static?void?loop(int[]?aa,?Closure?c)?{ ????for?(int?i?=?0;?i?<?aa.length;?i++)?{ ????????c.call(aa[i]) ????} ????println?'?' } | static?void?loop(int[]?aa,?Closure?c)?{ ????for?(int?i?=?0;?i?<?aa.length;?i?+=?2)?{ ????????c.call(aa[i]) ????} ????println?'?' } |
總結(jié),閉包本身并沒(méi)什么難點(diǎn),關(guān)鍵是怎樣合理的設(shè)計(jì)一個(gè)接受Closure類型參數(shù)的方法。從GDK的方法也可以看出,大多數(shù)接受閉包的方法都是和數(shù)組迭代有關(guān)(也即循環(huán))。
Definition
???
/*
????????1.?變量是用來(lái)裝“數(shù)據(jù)”的,閉包就是用來(lái)裝“操作”的
????????2.?和定義一個(gè)方法一樣,閉包也可以有入?yún)?br />???????
*/
????????Closure?p?
=
?{x?
->
????????????print?x?
+
?
'
?
'
????????}
????????[
1
,?
2
,?
3
].each(p)
????????[
4
,?
5
,?
6
].each({x?
->
?
//
?閉包是可以匿名的
????????????print?x?
+
?
'
?
'
????????})
????????[
7
,?
8
,?
9
].each?{x?
->
?
//
?括號(hào)是可以省略的
????????????print?x?
+
?
'
?
'
????????}
????????[
10
,?
11
,?
12
].each?{?
//
?it是默認(rèn)的參數(shù)名字,所以這里連入?yún)⒌亩x都省了
????????????print?it?
+
?
'
?
'
????????}
Using
package?jcat.bit
class?Test?{
????/*
????1.?閉包是對(duì)象,是Closure類的實(shí)例,所以:
????????1)可以在類里定義Closure類型的屬性
????????2)可以在方法里定義Closure類型的變量
????????3)可以定義一個(gè)方法,接收Closure類型的參數(shù)
????2.?閉包又有方法特質(zhì),畢竟它裝的是“操作”,甚至可以像調(diào)用方法一樣調(diào)用閉包
?????*/
????static?final?Closure?PRINT_STR?=?{??//?屬性(類變量)
????????println?it
????}
????static?void?main(String[]?a)?{
????????/*
????????閉包類似Java的內(nèi)部類,區(qū)別是閉包只有單一的方法可以調(diào)用,但可以有任意的參數(shù),
????????閉包用“{}”括起,“->”前面是參數(shù),后面是處理語(yǔ)句,可以直接調(diào)用,也可以使
????????用call調(diào)用。不管那種調(diào)用,最后groovy編譯器都會(huì)把編譯成對(duì)doCall方法的調(diào)用,
????????這是groovy對(duì)閉包的一個(gè)隱藏方法。
?????????*/
????????PRINT_STR("像方法一樣調(diào)用")
????????PRINT_STR.call("作為Closure的實(shí)例,再調(diào)用相應(yīng)的方法")
????????Closure?printLength?=?{String?s?->??//?局部變量
????????????println?s.length()
????????}
????????printLength("AAA")
????????/*
????????通常,操作是死的,我們能動(dòng)態(tài)代入的是“數(shù)據(jù)”。
????????閉包使得我們可以動(dòng)態(tài)的代入一段“操作”。
????????“閉包是可以用作方法參數(shù)的代碼塊。”
?????????*/
????????closureAsParameter(null,?printLength)
????????closureAsParameter("BBB",?PRINT_STR)
????}
????static?void?closureAsParameter(String?s,?Closure?c)?{
????????if?(s?!=?null)?{
????????????c.call(s)
????????}
????}
}
-----------------------------------------------------------------
附上一個(gè)Java的匿名內(nèi)部類的例子,用來(lái)和閉包對(duì)比一下。
package?jcat.bit;
public?class?AnonymousInnerClass?{
????public?static?void?main(String[]?args)?{
????????AbsClass?a?=?new?AbsClass()?{
????????????public?void?foo(String?s)?{
????????????????System.out.println(s);
????????????}
????????};
????????a.foo("ABC");
????????AbsClass?b?=?new?AbsClass()?{
????????????public?void?foo(String?s)?{
????????????????System.out.println(s.length());
????????????}
????????};
????????b.foo("ABC");
????}
}
abstract?class?AbsClass?{
????public?abstract?void?foo(String?s);
}
2008
10-25 Bind the thief's arms with rope.
10-26 Beer tests bitter.
10-27 This pocketknife has two blades.
10-28 If you don't do the work well, you will incur blame.
10-29 My mind was a total blank.
10-30 A blast of wind stirred up the dust.
10-31 The two brothers bled for their country and died happily.
11-1? His manner was a blend of friendliness and respect.
11-2 He gets an awful bloody nose.
11-3 The roses are in bloom.
11-4 The mother often boasts to the neighbors about the success of her children.
11-5 It is very bold of them to venture to travel by sea.
11-6 The bolts are all tight enough.
11-7 The terrorists planted a bomb in the building.
11-8 Comment interests form a bond between us.
11-9 I've booked you in at the hotel.
11-10 China is having a great boom in real estate.
11-11 This new technology will boost the production by 30% next year.
11-12 The criminal escaped over the border.
11-13 I am bored by his tedious talk.
11-14 The football bounced off the goal-post.
11-15 You are bound to succeed.
11-16 The new boundaries of the country were fixed after war.
11-17 The arrow was still held in the bow.
11-18 The brake didn't work.
11-19 He has his own brand of humour.
11-20 He has traveled the length and breadth of China.
11-21 Tom was bred up as a sailor.
11-22 We enjoyed the cool breeze that came from the lake.
11-23 Next Sunday Alvon will become AFu's bride.
11-24 Be brief and to the point.
最近BI的項(xiàng)目不忙,抽空懷念了一下編程技術(shù):
1. <Flex 3> 同事給了我份Flex的教程,把前三章看了一下,有了初步的了解;FlexBuilder也用了一把,不錯(cuò),效果很絢麗。
2. <IDEA 8> 恰逢IDEA 8 EAP (Early Access Preview)發(fā)布,搞了一個(gè)裝上試試。主要試了試對(duì)Flex的支持,感覺(jué)還有待提升。另外IDEA對(duì)內(nèi)存的消耗似乎越來(lái)越多了,沒(méi)做深入體驗(yàn)。
3. <Grails 1.0.3> 拿出了小二去年送我的生日禮物《Grails權(quán)威指南》,翻了翻,Hello World一會(huì)就做好了。打算再進(jìn)一步體驗(yàn)一下。
這是飛俠兄做的Flex網(wǎng)站,很好玩。
2008
國(guó)慶這個(gè)假放的,一直沒(méi)背單詞,又要慢慢追趕了。
9-25
All bacteria are larger than viruses.
9-26
The thief has gotten into the room off the balcony.
9-27
The treaty bans all nuclear tests.
9-28
On their way back home, they encountered a band of robbers.
9-29
We heard the bang of a gun.
9-30
The company went bankrupt.
10-1
The patriots hold aloft the banner of independence.
10-2
He opened a snake bar.
They barred the street to traffic.
10-3
The path leads to a bare hill.
10-4
He barely remembered anything she has said that day.
10-5
I make a fair bargain with the shopkeeper.
10-6
The dog always barks at strangers.
10-7
The horses seemed to be satisfied with the comfortable barn.
10-8
The river is a natural barrier between these two nations.
10-9
Baseball is the national sport of the USA.
10-10
Charity towards others is the basis of her philosophy.
10-11
The garden was bathed in moonlight.
10-12
They were faced with a battery of questions.
10-13
She spent her summer vacation in Sanya bay.
10-14
Beams support the roof of a house.
10-15
I cannot bear BB's nagging any longer.
10-16
He has a dense beard.
10-17
I have lost my bearings in all this mass of facts.
10-18
XX saves money on behalf of BB.
10-19
He behaves respectfully toward the elderly.
10-20
She was beloved of all who knew her.
10-21
Fresh air and good food are beneficial to one's health.
10-22
I'll bet you that they will win the next game.
10-23
The service included some readings from the Bible.
10-24
The dealers are bidding against each other at the auction.
2008
8-25
I saw the arrest of the thief.
8-26
The artificial flowers are quite beautiful.
8-27
Please assemble everybody in my office at 3'o clock.
8-28
It is hard to assess the impact of the war.
8-29
The firm's assets were taken over by the bank.
8-30
We assigned tomorrow morning for our meeting.
8-31
She spent most of her time associating with her friends.
9-1
I assume that you have heart the news.
9-2
I proceeded alone on the assumption that he would help.
9-3
He was assured a well paying job upon graduation.
9-4
Chinese athletes won many golden medals in the Olympic Games.
9-5
Attach a label to your suitcase.
9-6Finally he attained his goal.
9-7
Her work attitude was poor.
9-8
The defendant was represented by his attorney.
9-9
What a singularly attractive lady!
9-10
My mother attributes her good health to careful living.
9-11
Many works of literature and art have a wide and devoted audience.
9-12
You will get an automatic increase in pay every year.
9-13
Some sailboats have auxiliary engines.
9-14
There are no tickets available for Friday's performance.
9-15
NY's avenue is famous for its advertising industry.
9-16
He avoid answering my question.
9-17
We have awaited your coming for days.
9-18
The university awarded him an honorary degree.
9-19
We are fully aware of the gravity of the situation.
9-20
I feel awful this morning.
9-21
He feel awkward with women.9-22
He was a reporter by background.
9-23
He made a backward step.
9-24
Bacon and eggs are my favourite foods.
世界強(qiáng)隊(duì)從來(lái)不是靠抽簽抽出來(lái)的,中國(guó)男籃,我愛(ài)你!
“進(jìn)場(chǎng)的時(shí)候,我們把手放在一起,把自己交給這支球隊(duì),同時(shí)也把這支球隊(duì)扛在自己肩上,我們所有的人都在為這個(gè)球隊(duì)努力。” -- 大大的姚明
中國(guó)體操男團(tuán),背負(fù)四年的壓力,重獲金牌,超感人;
中國(guó)男籃vs西班牙,把世錦賽冠軍逼到打加時(shí),雖敗猶榮;
中國(guó)男足都是Sha Bi,窩囊廢。
又堅(jiān)持了一個(gè)月,中間短了4、5天,后來(lái)靠每天多背一個(gè),給補(bǔ)了回來(lái)。
7/25/2008
It is very essential to analyze the causes of his failure.
7/26/2008
This is an old family firm founded by their French ancestor.
7/27/2008
Can you anchor the boat in this storm?
7/28/2008
His family has lived in this ancient city for more than two centuries.
7/29/2008
The roof is at an angle of 120 degrees to the walls.
I would like to hear your angle in this dispute.
7/30/2008
The whole nation celebrated cheerfully the fiftieth anniversary of the founding of the PRC.
7/31/2008
These flies are annoying me.
We can annoy the enemy by air raids.
8/1/2008
BB's thesis was published in the college annual.
8/2/2008
We are not anticipating that there will be much trouble.
8/3/2008
The antique dealer has a display of his valuable antiques.
8/4/2008
He caused his wife great anxiety by driving a long distance alone.
8/5/2008
It's too late now, anyhow.
8/6/2008
It was apparent that they all understood.
8/7/2008
We are appealing for money to build a teacher's club.
8/8/2008
He had no appetite to fight.
8/9/2008
He won standing applause after he ended his speech.
8/10/2008
This is an appliance for opening cans.
8/11/2008
That pretty lady is a hopeful applicant for the position.
8/12/2008
They applied to return to China.
8/13/2008
They arranged an appointment for next week.
8/14/2008
We really appreciate the peace and quite of the countryside.
They deeply appreciate his thoughtfulness.
8/15/2008
The professor is easy to approach
8/16/2008
It is appropriate that you should save some money in case you lose your job.
8/17/2008
The decision met the committee's approval.
8/18/2008
His statement is approximate to the truth.
8/19/2008
One should not make an arbitrary decision as to what to do in the future.
8/20/2008
DXP is called the general architect of the construction of socialist modernizations in China.
8/21/2008
Don't argue with me, just do as you are told.
8/22/2008
At later stage, there arose an new problem which seemed insoluble.
8/23/2008
We aroused him from his deep sleep.
8/24/2008
She has arranged numerous contacts between? XX and BB.