Skip to content

Commit 15c478b

Browse files
committed
[Feature] java的闭包,用内部类实现
1 parent ab8980d commit 15c478b

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.coderising.myknowledgepoint.closure;
2+
3+
/**
4+
* Created by thomas_young on 27/8/2017.
5+
*/
6+
public class Milk {
7+
8+
public final static String name = "纯牛奶";//名称
9+
10+
private static int num = 16;//数量
11+
12+
public Milk()
13+
{
14+
System.out.println(name+":16/每箱");
15+
}
16+
17+
/**
18+
* 闭包
19+
* @return 返回一个喝牛奶的动作
20+
*/
21+
public Active HaveMeals()
22+
{
23+
return () -> {
24+
if(num == 0)
25+
{
26+
System.out.println("木有了,都被你丫喝完了.");
27+
return;
28+
}
29+
num--;
30+
System.out.println("喝掉一瓶牛奶");
31+
};
32+
}
33+
34+
/**
35+
* 获取剩余数量
36+
*/
37+
public void currentNum()
38+
{
39+
System.out.println(name+"剩余:"+num);
40+
}
41+
}
42+
43+
/**
44+
* 通用接口
45+
*/
46+
interface Active
47+
{
48+
void drink();
49+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.coderising.myknowledgepoint.closure;
2+
3+
/**
4+
* Created by thomas_young on 27/8/2017.
5+
*/
6+
public class Person {
7+
8+
public static void main(String[] args) {
9+
//买一箱牛奶
10+
Milk m = new Milk();
11+
12+
Active haveMeals = m.HaveMeals();
13+
14+
//没事喝一瓶
15+
haveMeals.drink();
16+
//有事喝一瓶
17+
haveMeals.drink();
18+
19+
//看看还剩多少?
20+
m.currentNum();
21+
m = null;
22+
haveMeals.drink(); // 闭包会导致资源不被回收
23+
haveMeals.drink();
24+
haveMeals.drink();
25+
haveMeals.drink();
26+
haveMeals.drink();
27+
haveMeals.drink();
28+
haveMeals.drink();
29+
haveMeals.drink();
30+
haveMeals.drink();
31+
haveMeals.drink();
32+
haveMeals.drink();
33+
haveMeals.drink();
34+
haveMeals.drink();
35+
haveMeals.drink();
36+
haveMeals.drink();
37+
haveMeals.drink();
38+
haveMeals.drink();
39+
}
40+
41+
}

0 commit comments

Comments
 (0)