什么是空对象模式
用一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
适用场景
提供默认行为,提供默认值。
abstract class AbstractCustomer {
protected String name;
public abstract boolean isNull();
public abstract String getName();
}
class RealCustomer extends AbstractCustomer {
public RealCustomer(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isNull() {
return false;
}
}
class NullCustomer extends AbstractCustomer {
@Override
public String getName() {
return "Not Available in Customer Database";
}
@Override
public boolean isNull() {
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 NullObjectPattern {
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());
//输出:
//Customers
//Rob
//Not Available in Customer Database
//Julie
//Not Available in Customer Database
}
}
Java8提供的Optional
public class OptionalDemo {
public static void main(String[] args) {
//JAVA的败笔之一 就是提供了null这个默认值 使得NPE到处出现,空指针异常编译时无法发现,运行时系统崩溃
// String s = null;
// System.out.println(s.length()); //NullPointerException
//改进如下
// if (null != s) {
// System.out.println(s.length());
// }
//JDK8 提供了Optional
//默认EMPTY值
Optional<Object> empty = Optional.empty();
System.out.println(empty);//Optional.empty
System.out.println("-----------------------------");
String str1=null;
// Optional<String> s1 = Optional.of(str1);//NullPointerException
Optional<String> s1 = Optional.ofNullable(str1);//NullPointerException
System.out.println(s1);//Optional.empty
// System.out.println(s1.get());//NullPointerException
System.out.println(s1.isPresent());//false
System.out.println(s1.orElse("默认值"));//默认值
System.out.println("-----------------------------");
String str2="test";
Optional<String> s2 = Optional.of(str2);
System.out.println(s2);//Optional[test]
Optional<String> s3 = Optional.ofNullable(str2);
System.out.println(s3);//Optional[test]
System.out.println(s3.get());//test
System.out.println(s3.isPresent());//true
System.out.println(s3.orElse("默认值"));//test
}
}