Matlab混入模式(Mixin)

时间:2023-03-10 06:29:30
Matlab混入模式(Mixin)

Mixin是一种类,这种类包含了其他类要使用的特性方法,但不必充当其他类的父类。Matlab无疑是支持多继承的。我们可以利用 Matlab 的这种特性,实现一种叫做 Mixin 的类。MixIn的目的就是给一个类增加多个功能,这样,在设计类的时候,我们优先考虑通过多重继承来组合多个MixIn的功能,而不是设计多层次的复杂的继承关系。(见https://blog.****.net/qq_31156277/article/details/80659537)

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

Matlab混入模式(Mixin)

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.****.net/cwy0502/article/details/90924330

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

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

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

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