Using abstract classes in Matlab (no properties)

Suppose we have one abstract class:

classdef ACalculation < handle methods (Abstract) [result] = calculate (this, data); plot (this, data, limX, limY); end end 

And some other classes that implement ACalculation

 classdef Maximum < ACalculation methods function [result] = calculate (this, data) %... end function plot (this, data, limX, limY) %... end end 

I give all the necessary information to the functions of the implementation class, so I do not need any properties. Therefore, it seems to me that I need static classes. But if I have static classes, I have a problem with calling these functions. I would like to do something like this:

 criteria = Maximum(); %...... result = criteria.calculate(data); 

Is inheritance wrong? Should I ignore Matlab's tips for changing functions to static? What else could I do here?

+7
source share
2 answers

I think in this case the implementation of the static interface is pretty good. Define your classes as follows:

 classdef ACalculation < handle methods (Abstract,Public,Static) [result] = calculate (data); plot (data, limX, limY); end end classdef Maximum < ACalculation methods (Public,Static) function [result] = calculate (data) %... end function plot (data, limX, limY) %... end end 

Then you can write a function that expects an ACalculation type:

  function foo(acalc,data) assert(isa(acalc,'ACalculation')); acalc.calculate(data); acalc.plot(data,[100 200]); end 

Then create an empty Maximum instance and pass it to foo :

  foo ( Maximum.empty(0), [1 2 3]); 

If you want to change the calculation method, call

  foo ( Minimum.empty(0), [1 2 3]); 

When you say that such a pattern will not work, you think as a Java / C # / C ++ developer. But unlike C ++, where the static and virtual keywords cannot coexist, Matlab does not have such a restriction, because everything is executed at runtime, and the "instance" can be empty or an array of n elements.

+5
source

If calculate is the static Maximum', you would use 'result = Maximum.calculate(data) method Maximum', you would use 'result = Maximum.calculate(data) to call it without instantiating the criteria .

This is not (necessarily) a bad way to use inheritance or bad advice from MATLAB.

0
source

All Articles