当前位置: 移动技术网 > IT编程>软件设计>设计模式 > Matlab空对象模式

Matlab空对象模式

2019年06月19日  | 移动技术网IT编程  | 我要评论

在空对象模式(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();

参考资料:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网