这是我的想法。我将创建一个名为Developer
的类,该类将包含一个Developable
对象作为属性。称为Developable
的接口将具有3个抽象方法,getProperty
,setProperty
和meval
。我将限制访问这些方法Developable
和Developer
。这里有以下一些示例代码:
的classdef
为Developable
classdef (Abstract) Developable < handle
methods (Abstract, Access = {?Developable, ?Developer})
propVal = getProperty(This, propName)
This = setProperty(This, propName, propVal)
varargout = meval(This, methodName, varargin)
end
end
和Developer
classdef Developer < handle
properties
[email protected]
end
methods
function This = Developer(DevObj)
if isa(DevObj, 'Developable')
This.DevObj = DevObj;
warnId = '''Developer:debugUseOnly''';
warnMessage = ['''The Developer class should only be used ' ...
'temporarily to gain access to private and ' ...
'protected class members. Do not use in any ' ...
'permanent manner. Instead contact the owner ' ...
'of the class you wish to modify, and work out a ' ...
'solution.'''];
warnStr = ['warning(' warnId ',' warnMessage ')'];
evalin('caller', warnStr)
else
errorId = 'Developer:nonDevelopableObject';
errorMsg = 'DevObj must be a Developable Object';
error(errorId, errorMsg)
end
end
function propVal = getProperty(This, propName)
propVal = This.DevObj.getProperty(propName);
end
function setProperty(This, propName, propVal)
This.DevObj.setProperty(propName, propVal);
end
function varargout = meval(This, methodName, varargin)
if nargout > 0
out = cell(1, nargout);
[out{:}] = This.DevObj.meval(methodName, varargin{:});
varargout = out;
else
This.DevObj.meval(methodName, varargin{:});
end
end
end
end
这似乎为我工作,但也有一些问题吧:
有没有人有更好的方法来解决我的问题,或解决我上面列出的一些问题?
下面是一个例子Developable
类:
classdef DevTest < Developable
properties (Access = private)
privateProp = 'This property is private';
end
methods (Access = private)
function privateMethod(This)
disp('You''ve gained access to a private method!')
end
end
methods (Access = {?Developable, ?Developer})
function propVal = getProperty(This, propName)
propVal = This.(propName);
end
function This = setProperty(This, propName, propVal)
This.(propName) = propVal;
end
function varargout = meval(This, methodName, varargin)
if nargout > 0
varargout = cell(nargout, 1);
[varargout{:}] = This.(methodName)(varargin{:});
else
This.(methodName)(varargin{:});
end
end
end
end
我很努力地看到这一点,在这里......如果您打算编写代码来打破MATLAB的OO范例,那么为什么还要麻烦编写OO代码?听起来像是给我带来麻烦......也许如果你对最终目标提供了一个不太抽象的描述,那么可能会更容易帮助你想出一个有形的设计。 – wakjah 2013-05-11 09:33:22