OOP: How to let a bunch of methods behave differently depending in the type of input?

조회 수: 1 (최근 30일)
Let's imagine we have a Class called OOP_Base and lots of subclasses like "OOP_Mult5" that implement the "Apply" Method defined "abstract" in the OOP_Base class.
I like to convert accidental char inputs for all those classes to double. I don't want to implement a isa(in,'char') in all hundred methods "OOP_Mult5" and so on.
Is it possible to put the "isa()"-query and a str2num() if the input is char in the OOP_Base for all subclasses?
% OOP_Base:
classdef OOP_Base
methods (Abstract = true)
result = Apply(in)
end
end
classdef OOP_Mult5 < OOP_Base
methods (Static = true)
function result = Apply(in)
result = 5*in;
end
end
end
P.S.: This is just an example to illustrate my problem. In reality I have to deal with lots of filters that should work with a special "Image"-class but also with simple R,G,B vectors.
Thank you very much in advance for your help,
Jan

채택된 답변

Matt J
Matt J 2012년 10월 9일
편집: Matt J 2012년 10월 9일
Instead of making Apply() abstract, make it call abstract functions:
classdef OOP_Base
methods result=Apply(in)
if ischar(in), in=str2num(in); end
result=ApplyMain(in);
end
methods (Abstract = true)
result = ApplyMain(in)
end
end
classdef OOP_Mult5 < OOP_Base
methods (Static = true)
function result = ApplyMain(in)
result = 5*in;
end
end
end

추가 답변 (1개)

Jan Froehlich
Jan Froehlich 2012년 10월 13일
Hi Matt,
thank you very much, I had to play around a bit with your code but now it works fine:
classdef A
methods
function Apply(this,in)
disp('In abstract parent');
if isa(in,'char'), in=str2double(in); disp('Is char'); end
if isa(in,'double'), disp('Is double'); end
disp(mfilename('class'))
this.ApplyWorker(in);
end
end
methods(Abstract,Static)
ApplyWorker(in);
end
end
classdef B < A
methods (Static = true)
function ApplyWorker(in)
disp('In B');
disp(in*5);
end
end
end
classdef C < A
methods (Static = true)
function ApplyWorker(in)
disp('In C');
disp(in*10)
end
end
end
Typing:
clear classes
b = B;
c = C;
b.Apply(2)
b.Apply('2')
c.Apply(2)
c.Apply('2')
results in:
In abstract parent
Is double
A
In B
10
In abstract parent
Is char
Is double
A
In B
10
In abstract parent
Is double
A
In C
20
In abstract parent
Is char
Is double
A
In C
20
Thanks again for your fast help!
Jan

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by