空对象模式

1.空对象模式简介

在空对象模式(Null Object Pattern)中,一个空对象取代对 NULL 对象实例的检查。Null 对象不是检查空值,而是变为返回一个不做任何动作
的对象。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将
无缝地使用在需要检查空值的地方。

2.测试Demo

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;
    }
    public boolean isNull() {
        return false;
    }
    public String getName() {
        return name;
    }
}

class NullCustomer extends AbstractCustomer {
    public boolean isNull() {
        return true;
    }
    public String getName() {
        return "Couldn't get in database";
    }
}

class CustomerFactory {
    /* 必须加static后才能在static方法中使用,使用static修饰为常量也不行,这一点可能
     * 和C++不一样 */
    private static final String names[] = {"jone", "july", "marel", "koko", "kity"};

    public static AbstractCustomer getCustomer(String name) {
        for (int i = 0; i < names.length; i++) {
            if (names[i].equalsIgnoreCase(name)) {
                return new RealCustomer(name);
            }
        }
        return new NullCustomer();
    }
}

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

        AbstractCustomer c1 = CustomerFactory. getCustomer("koko");
        System.out.println(c1.getName());

        AbstractCustomer c2 = CustomerFactory. getCustomer("fuxi");
        System.out.println(c2.getName());

        AbstractCustomer c3 = CustomerFactory. getCustomer("jone");
        System.out.println(c3.getName());
    }
}

/*
$ java NullPatternDemo 
koko
Couldn't get in database
jone

*/

 

 

参考:http://www.runoob.com/design-pattern/null-object-pattern.html

 

posted on 2019-04-18 23:33  Hello-World3  阅读(114)  评论(0编辑  收藏  举报

导航