NPE 를 피하기 위한 디자인 패턴
public abstract class AbstractCustomer {
protected String personName;
public abstract boolean isNull();
public abstract String getCustomer();
}
public class RealCustomer extends AbstractCustomer {
public RealCustomer(String customerName) {
this.personName = customerName;
}
@Override
public boolean isNull() {
return false;
}
@Override
public String getCustomer() {
return this.personName;
}
}
public class NullCustomer extends AbstractCustomer {
@Override
public boolean isNull() {
return true;
}
@Override
public String getCustomer() {
return "No customer";
}
}
public class Database {
private List<String> customerNames;
public Database() {
this.customerNames = new ArrayList<>();
this.customerNames.add("A");
this.customerNames.add("B");
this.customerNames.add("C");
this.customerNames.add("D");
}
public boolean existsCustomer(String name) {
return customerNames.contains(name);
}
}
public class CustomerFactory {
private Database database;
public CustomerFactory() {
this.database = new Database();
}
public AbstractCustomer getCustomer(String name) {
if (checkName(name)) {
return new RealCustomer(name);
}
return new NullCustomer();
}
private boolean checkName(String name) {
return database.existsCustomer(name);
}
}
결론적으로 Customer 객체를 추상화해 isNull() 메서드를 사용하게 된다.
CustomerFactory
를 거쳐 customer를 가져와 NPE를 피할 수 있다.