空对象模式
2019-07-28  本文已影响0人 
码上述Andy
1.概述
平时开发中避免过多的判空检查,空对象模式很好的避免了这种情况出现,当为空或者不存在的时候返回一个空对象,避免程序NullPointException异常发生。
2.UML结构图
image.png
3.代码实现:以班级点名为例
/**
 * Created by zhouwen on 2019/6/18 16:35
 */
public interface AbstractInterface {
    void callName();
}
/**
 * Created by zhouwen on 2019/6/18 16:37
 */
public class RosterImpl implements AbstractInterface {
    @Override
    public void callName() {
        Logger.getLogger("RosterImpl").info("not null!!");
    }
}
/**
 * Created by zhouwen on 2019/6/18 16:33
 */
public class NullImpl空对象 implements AbstractInterface {
    @Override
    public void callName() {
        Logger.getLogger("NullImpl空对象").info("null pointer!!");
    }
}
/**
 * Created by zhouwen on 2019/6/18 16:39
 */
public class RosterFactory花名册 {
    private static final int[] studentNums = {1, 2, 3,4,5,6,7,8};
    public static AbstractInterface getCustomer(int studentNum) {
        int length = studentNums.length;
        for (int i = 0; i < length; i++) {
            if (studentNums[i] == studentNum) {
                return new RosterImpl();
            }
        }
        return new NullImpl空对象();
    }
}
/**
 * Created by zhouwen on 2019/7/28 10:15
 */
public class RosterClient {
    public void main() {
//        AbstractInterface customer1 = RosterFactory花名册.getCustomer(1);
//        customer1.callName();
//        AbstractInterface customer2 = RosterFactory花名册.getCustomer(2);
//        customer2.callName();
//        AbstractInterface customer3 = RosterFactory花名册.getCustomer(33);
//        customer3.callName();
        AbstractInterface customer;
        for (int i=0; i <36; i++){
            customer = RosterFactory花名册.getCustomer(i);
            customer.callName();
        }
    }
}