Matlab混入模式(Mixin)

Mixin是一種類,這種類包含了其他類要使用的方法,但不必充當其他類的父類。Matlab無疑是支持多繼承的。我們可以利用 Matlab 的這種特性,實現一種叫做 Mixin 的類。MixIn的目的就是給一個類增加多個功能,這樣,在設計類的時候,我們優先考慮通過多重繼承來組合多個MixIn的功能,而不是設計多層次的複雜的繼承關係。

Automobile.m

classdef Automobile < handle
    methods(Abstract)
        dispAutomobile(~);
    end
end

Car.m 

classdef Car < Automobile
    methods
        function dispAutomobile(~)
            disp("Car");
        end
    end
end

Bus.m

classdef Bus < Automobile
    methods
        function dispAutomobile(~)
            disp("Bus");
        end
    end
end

Color.m (混入類Mixin)

classdef Color < handle
    methods(Abstract)
        dispColor(~);
    end
end

Red.m (混入類Mixin)

classdef Red < Color
    methods
        function dispColor(~)
            disp("Red");
        end
    end
end

Blue.m (混入類Mixin)

classdef Blue < Color
    methods
        function dispColor(~)
            disp("Blue");
        end
    end
end

RedCar.m

classdef RedCar < Car & Red
    methods
        function dispThis(obj)
            disp("RedCar is:");
            obj.dispColor();
            obj.dispAutomobile();
        end
    end
end

BlueBus.m

classdef BlueBus < Bus & Blue
    methods
        function dispThis(obj)
            disp("BlueBus is:");
            obj.dispColor();
            obj.dispAutomobile();
        end
    end
end

 測試代碼:

rc = RedCar();
rc.dispThis();

bb = BlueBus();
bb.dispThis();

運行結果:

參考資料:

https://blog.csdn.net/cwy0502/article/details/90924330

https://blog.csdn.net/u012814856/article/details/81355935

https://blog.csdn.net/weixin_34006468/article/details/87266145

https://blog.csdn.net/zhongbeida_xue/article/details/88601352

https://blog.csdn.net/u013985879/article/details/82155892

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