-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCourse01CodeUse.java
56 lines (47 loc) · 1.21 KB
/
Course01CodeUse.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.java8.lambda.chapter4;
import java.util.function.Supplier;
/**
* 在代码中使用 Lambda 表达式
*
* @author hzweiyongqiang
*
*/
public class Course01CodeUse {
private boolean debug = true;
public boolean isDebugEnabled() {
return debug;
}
public void debug(String message) {
if (isDebugEnabled()) {
System.out.println(message);
}
}
public String expensiveOperation() {
return "";
}
/**
* 使用 isDebugEnabled 方法降低日志性能开销
*/
public void example() {
Course01CodeUse logger = new Course01CodeUse();
if (logger.isDebugEnabled()) {
logger.debug("Look at this: " + expensiveOperation());
}
}
/**
* 使用 Lambda 表达式简化日志代码
*/
public void exampleWithLambda() {
Course01CodeUse logger = new Course01CodeUse();
logger.debug(() -> "Look at this: " + expensiveOperation());
}
/**
* 启用 Lambda 表达式实现的日志记录器
* @param message
*/
public void debug(Supplier<String> message) {
if (isDebugEnabled()) {
debug(message.get()); // 如果使用 Predicate ,就应该调用 test 方法,如果使用 Function ,就应该调用 apply 方法。
}
}
}