-
Notifications
You must be signed in to change notification settings - Fork 1
/
NullObject.java
65 lines (50 loc) · 1.02 KB
/
NullObject.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
// Null object pattern
package behavioral.nullobject;
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 NullObjectDemo
{
public static void main(String[] args) {
Log log = new NullLog();
BankAccount account = new BankAccount(log);
account.deposit(100);
}
}