美文网首页Android技术知识Android开发
空对象模式--- Pattern Null Object

空对象模式--- Pattern Null Object

作者: Dotry | 来源:发表于2018-10-11 20:07 被阅读11次

    模式的定义

    空对象模式(Null Object Pattern)定义如下:
    Provide an object as a surrogate for the lack of an object of a given type. The Null Object provides intelligent do nothing behavior, hiding the details from its collaborators.

    UML类图

    20161117124923108.png

    模式的简单实现:

    先定义一个AbstractObject类:

    /**
     * 抽象类
     */
    public abstract class AbstractObject {
        public int id;
        public String name;
        //抽象方法
        public abstract void doAction();
        public abstract boolean isNull();
    }
    

    再定义一个实现类:ConcreteObject

    public class ConcreteObject extends AbstractObject {
        public ConcreteObject(int id,String name) {
            super.id = id;
            super.name = name;
        }
    
        @Override
        public void doAction() {
            System.out.println("id:"+id+"--name:"+name+"---doAction()");
        }
    
        @Override
        public boolean isNull() {
            return false;
        }
    }
    

    我们再定义一个工厂方法类:ObjectFactory

    /**
     * 生成对象
     */
    public class ObjectFactory {
        public static AbstractObject creator(int id) {
            AbstractObject result = null;
            switch (id) {
                case 1:
                    result = new ConcreteObject(1, "hello");
                    break;
                case 2:
                    result = new ConcreteObject(2, "world");
                    break;
                default:
                    result = new NullObject();
                    break;
            }
            return result;
        }
    }
    

    客户端如下调用即可:

    public class Main {
        public static void main(String[] args) {
            AbstractObject aObject = ObjectFactory.creator(1);
            aObject.doAction();
            System.out.println("----------------------------");
            aObject = ObjectFactory.creator(2);
            aObject.doAction();
            System.out.println("----------------------------");
            aObject = ObjectFactory.creator(-1);
            System.out.println("is null"+aObject.isNull());
            aObject.doAction();
            System.out.println("----------------------------");
        }
    }
    

    而在没有采用此方式的情况下,我们需要在每次创建的时候做判空处理。

    相关文章

      网友评论

        本文标题:空对象模式--- Pattern Null Object

        本文链接:https://www.haomeiwen.com/subject/wxriaftx.html