1. 程式人生 > >十三、空對象模式

十三、空對象模式

clas author span abs package 數據 dem data obj

空對象模式其實就是定義一個對象用來處理默認的行為,代碼如下:

package test;

/**
 * 空對象模式
 * @author lay
 */
public class NullDemo {
    
    public static void main(String[] args) {
        String string = null;
        AbstractObj abstractObj;
        if (string == null) {
            abstractObj = new NULL();
        }else{
            abstractObj 
= new Data(); } abstractObj.say(); } } // 抽象 interface AbstractObj{ public void say(); } // 定義空對象 class NULL implements AbstractObj{ public void say(){ System.out.println("null"); } } // 定義數據對象 class Data implements AbstractObj{ public void say(){ System.out.println(
"not null"); } }

十三、空對象模式