本文主要介绍了Java中的委托以及lombok中Delegate注解。
首先看C#中的委托 https://www.runoob.com/csharp/csharp-delegate.html
重点
- C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。
- 委托的多播(Multicasting of a Delegate)
- 理解两个例子 https://projectlombok.org/features/Delegate.html
1 | public class DelegationExample { |
使用Lombok的写法
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
27public class DelegationExample {
private interface SimpleCollection {
boolean add(String item);
boolean remove(Object item);
}
(types=SimpleCollection.class)
private final Collection<String> collection = new ArrayList<String>();
public static void main(String[] args) {
DelegationExample delegationExample = new DelegationExample();
delegationExample.add("a"); // 实际上加入到了collection中了,也就是添加元素和删除元素委托给了collection来完成
}
/** 这部分代码被省略掉了
@SuppressWarnings("all")
public boolean add(final String item) {
return this.collection.add(item);
}
@SuppressWarnings("all")
public boolean remove(final Object item) {
return this.collection.remove(item);
}
**/
}
第二个例子,省了不少代码
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class ExcludesDelegateExample {
long counter = 0L;
private interface Add {
boolean add(String x);
boolean addAll(Collection<? extends String> x);
}
private final Collection<String> collection = new ArrayList<String>();
public boolean add(String item) {
counter++;
return collection.add(item);
}
public boolean addAll(Collection<? extends String> col) {
counter += col.size();
return collection.addAll(col);
}
"all") (
public int size() {
return this.collection.size();
}
"all") (
public boolean isEmpty() {
return this.collection.isEmpty();
}
"all") (
public boolean contains(final Object arg0) {
return this.collection.contains(arg0);
}
"all") (
public java.util.Iterator<String> iterator() {
return this.collection.iterator();
}
"all") (
public Object[] toArray() {
return this.collection.toArray();
}
"all") (
public <T extends Object>T[] toArray(final T[] arg0) {
return this.collection.<T>toArray(arg0);
}
"all") (
public boolean remove(final Object arg0) {
return this.collection.remove(arg0);
}
"all") (
public boolean containsAll(final java.util.Collection<?> arg0) {
return this.collection.containsAll(arg0);
}
"all") (
public boolean removeAll(final java.util.Collection<?> arg0) {
return this.collection.removeAll(arg0);
}
"all") (
public boolean retainAll(final java.util.Collection<?> arg0) {
return this.collection.retainAll(arg0);
}
"all") (
public void clear() {
this.collection.clear();
}
}
1 | class ExcludesDelegateExample { |