这是我的想法。我将创建一个名为的类,该类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
DevObj@Developable
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