Matlab空對象模式(Null Object)

在空對象模式(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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章