1. 闭包代表(定义)了一段代码(操作):光看这一句,其实方法也能实现相同的功能呀。
2. 闭包可以作为方法的参数:这才是闭包的特殊之处和真正意义。
下面演示一个只有闭包能做,方法做不到的例子。
方法的作用是提炼共性,再代之以不同的参数。即对不同的“数据”进行相同的“操作”。从3个loop可以看出:
Comm1:相同的数据
Comm2:相同的for循环
Diff1:循环体内执行的操作不同
Comm1很好搞定,参数aa就是提炼出的共性
Comm2看似是共性,却很难提炼,因为for循环和循环体内的操作实际是一个整体;Comm2被Diff1纠缠,3个loop是完全不同的3组操作,无法提炼。
比如,如果现在想要按照奇数循环,只能依次改动三个循环。
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]
+
'
'
}
|
下面我们看看闭包的强大之处,Comm1和Comm2都被很好的封装在了loop方法里;
Diff1则作为参数(闭包)传入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 + ' ' }
}
|
如果我们想要改变循环的方式,只需要改一处
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 ' ' } |
总结,闭包本身并没什么难点,关键是怎样合理的设计一个接受Closure类型参数的方法。从GDK的方法也可以看出,大多数接受闭包的方法都是和数组迭代有关(也即循环)。
posted @
2008-11-07 02:04 Jcat 阅读(1545) |
评论 (2) |
编辑 收藏
Definition
/*
1. 变量是用来装“数据”的,闭包就是用来装“操作”的
2. 和定义一个方法一样,闭包也可以有入参
*/
Closure p
=
{x
->
print x
+
'
'
}
[
1
,
2
,
3
].each(p)
[
4
,
5
,
6
].each({x
->
//
闭包是可以匿名的
print x
+
'
'
})
[
7
,
8
,
9
].each {x
->
//
括号是可以省略的
print x
+
'
'
}
[
10
,
11
,
12
].each {
//
it是默认的参数名字,所以这里连入参的定义都省了
print it
+
'
'
}
Using
package jcat.bit
class Test {
/*
1. 闭包是对象,是Closure类的实例,所以:
1)可以在类里定义Closure类型的属性
2)可以在方法里定义Closure类型的变量
3)可以定义一个方法,接收Closure类型的参数
2. 闭包又有方法特质,毕竟它装的是“操作”,甚至可以像调用方法一样调用闭包
*/
static final Closure PRINT_STR = { // 属性(类变量)
println it
}
static void main(String[] a) {
/*
闭包类似Java的内部类,区别是闭包只有单一的方法可以调用,但可以有任意的参数,
闭包用“{}”括起,“->”前面是参数,后面是处理语句,可以直接调用,也可以使
用call调用。不管那种调用,最后groovy编译器都会把编译成对doCall方法的调用,
这是groovy对闭包的一个隐藏方法。
*/
PRINT_STR("像方法一样调用")
PRINT_STR.call("作为Closure的实例,再调用相应的方法")
Closure printLength = {String s -> // 局部变量
println s.length()
}
printLength("AAA")
/*
通常,操作是死的,我们能动态代入的是“数据”。
闭包使得我们可以动态的代入一段“操作”。
“闭包是可以用作方法参数的代码块。”
*/
closureAsParameter(null, printLength)
closureAsParameter("BBB", PRINT_STR)
}
static void closureAsParameter(String s, Closure c) {
if (s != null) {
c.call(s)
}
}
}
-----------------------------------------------------------------
附上一个Java的匿名内部类的例子,用来和闭包对比一下。
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);
}
posted @
2008-11-06 18:50 Jcat 阅读(353) |
评论 (0) |
编辑 收藏
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.
posted @
2008-11-05 23:53 Jcat 阅读(296) |
评论 (0) |
编辑 收藏
最近BI的项目不忙,抽空怀念了一下编程技术:
1. <Flex 3> 同事给了我份Flex的教程,把前三章看了一下,有了初步的了解;FlexBuilder也用了一把,不错,效果很绚丽。
2. <IDEA 8> 恰逢IDEA 8 EAP (Early Access Preview)发布,搞了一个装上试试。主要试了试对Flex的支持,感觉还有待提升。另外IDEA对内存的消耗似乎越来越多了,没做深入体验。
3. <Grails 1.0.3> 拿出了小二去年送我的生日礼物《Grails权威指南》,翻了翻,Hello World一会就做好了。打算再进一步体验一下。
posted @
2008-11-04 22:04 Jcat 阅读(197) |
评论 (0) |
编辑 收藏
这是飞侠兄做的Flex网站,很好玩。
posted @
2008-10-22 21:14 Jcat 阅读(194) |
评论 (0) |
编辑 收藏
2008
国庆这个假放的,一直没背单词,又要慢慢追赶了。
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.
posted @
2008-10-14 00:20 Jcat 阅读(781) |
评论 (2) |
编辑 收藏
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.
posted @
2008-08-27 23:12 Jcat 阅读(339) |
评论 (2) |
编辑 收藏
世界强队从来不是靠抽签抽出来的,中国男篮,我爱你!
“进场的时候,我们把手放在一起,把自己交给这支球队,同时也把这支球队扛在自己肩上,我们所有的人都在为这个球队努力。” -- 大大的姚明
posted @
2008-08-16 21:56 Jcat 阅读(163) |
评论 (0) |
编辑 收藏
中国体操男团,背负四年的压力,重获金牌,超感人;
中国男篮vs西班牙,把世锦赛冠军逼到打加时,虽败犹荣;
中国男足都是Sha Bi,窝囊废。
posted @
2008-08-12 18:54 Jcat 阅读(222) |
评论 (0) |
编辑 收藏
又坚持了一个月,中间短了4、5天,后来靠每天多背一个,给补了回来。
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.
posted @
2008-07-28 22:23 Jcat 阅读(343) |
评论 (1) |
编辑 收藏