Matlab混入模式(Mixin)

25 篇文章 2 订阅
21 篇文章 1 订阅

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值