Matlab空對象模式

在空對象模式(Null Object Pattern)中,一個空對象取代 NULL 對象實例的檢查。Null 對象不是檢查空值,而是反應一個不作任何動做的關係。這樣的 Null 對象也能夠在數據不可用的時候提供默認的行爲。html

AbstractObject.mhtm

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.mblog

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

ObjectFactory.mget

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.mio

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

參考資料:function

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

相關文章
相關標籤/搜索