空对象模式

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
abstract class AbstractCustomer {
protected String name;

public abstract boolean isNil();

public abstract String getName();
}

class RealCustomer extends AbstractCustomer {

public RealCustomer(String name) {
this.name = name;
}

@Override
public String getName() {
return name;
}

@Override
public boolean isNil() {
return false;
}
}

class NullCustomer extends AbstractCustomer {

@Override
public String getName() {
return "Not Available in Customer Database";
}

@Override
public boolean isNil() {
return true;
}
}

class CustomerFactory {

public static final String[] names = {"Rob", "Joe", "Julie"};

public static AbstractCustomer getCustomer(String name) {
for (String s : names) {
if (s.equalsIgnoreCase(name)) {
return new RealCustomer(name);
}
}
return new NullCustomer();
}
}

public class NullObjectPatternDemo {
public static void main(String[] args) {

AbstractCustomer customer1 = CustomerFactory.getCustomer("Rob");
AbstractCustomer customer2 = CustomerFactory.getCustomer("Bob");
AbstractCustomer customer3 = CustomerFactory.getCustomer("Julie");
AbstractCustomer customer4 = CustomerFactory.getCustomer("Laura");

System.out.println("Customers");
System.out.println(customer1.getName());
System.out.println(customer2.getName());
System.out.println(customer3.getName());
System.out.println(customer4.getName());
}
}

空对象模式
https://wangqian0306.github.io/2021/design-null-object-pattern/
作者
WangQian
发布于
2021年7月22日
许可协议