Matlab空对象模式

在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。

AbstractObject.m

classdef AbstractObject < handle
    methods(Abstract)
        operation(~);
    end
end

 RealObject.m

classdef RealObject < AbstractObject
    properties
        name
    end
    methods
        function obj = RealObject(name)
            obj.name = name;
        end 
        function operation(obj)
            disp("This is object " + obj.name + " operation.");
        end
    end
end

NullObject.m

classdef NullObject < AbstractObject
    methods
        function operation(~)
            disp("This is NullObject");
        end
    end
end

ObjectFactory.m

classdef ObjectFactory < handle
    properties(Constant)
        names = ["matlab","pattern","design"];
    end
    methods(Static)
        function res = getObject(name)
            if(sum(ObjectFactory.names == name) > 0)
                res = RealObject(name);
            else
                res = NullObject();
            end
        end
    end
end

test.m

obj1 = ObjectFactory.getObject("matlab");
obj1.operation();
obj2 = ObjectFactory.getObject("null");
obj2.operation();

参考资料:

https://www.runoob.com/design-pattern/null-object-pattern.html

posted on 2019-06-19 00:37  sw-lab  阅读(400)  评论(0编辑  收藏  举报

导航