-
Notifications
You must be signed in to change notification settings - Fork 1
/
DynamicNullObject.java
84 lines (66 loc) · 1.73 KB
/
DynamicNullObject.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Dynamic null object pattern
package behavioral.nullobject.dynamicnullobject;
import java.lang.reflect.Proxy;
interface Log
{
void info(String msg);
void warn(String msg);
}
class ConsoleLog implements Log
{
@Override
public void info(String msg) {
System.out.println(msg);
}
@Override
public void warn(String msg) {
System.out.println("WARNING: " + msg);
}
}
class BankAccount
{
private Log log;
private int balance;
public BankAccount(Log log) {
this.log = log;
}
public void deposit(int amount)
{
balance += amount;
log.info("Deposited " + amount); // hard dependency on 'Log'
}
}
// Null object
final class NullLog implements Log
{
// Leave methods empty and fields default value
@Override
public void info(String msg) {
}
@Override
public void warn(String msg) {
}
}
class DynamicNullObjectDemo
{
// Dynamic null object construction here - utility static method
@SuppressWarnings("unchecked")
public static <T> T noOp(Class<T> itf)
{
return (T) Proxy.newProxyInstance(
itf.getClassLoader(),
new Class<?>[]{itf},
(proxy, method, args) ->
{
if (method.getReturnType().equals(Void.TYPE))
return null;
else
return method.getReturnType().getConstructor().newInstance();
});
}
public static void main(String[] args) {
Log log = noOp(Log.class); // at runtime, Java will construct a fake object conforming to the Log interface to check which interface to return
BankAccount account = new BankAccount(log);
account.deposit(100);
}
}