我想创建一个单独的MATLAB类作为全局注册表。注册表应存储使用唯一名称寻址的对象(来自handle
的某个类)。我想方便地访问存储类的属性而不需要临时变量,例如:
Registry.instance().addElement('name1', NewObject(...));
Registry.instance().get('name1').Value
Registry.instance().get('name2').Value = 1;
通过从()
中删除instance
,可以规避读出返回类的属性:
>> Equipment.instance.get('name1').Value
但是,使用赋值似乎并不容易,因为如注释中所述,点索引不能直接用于函数的输出而不分配给中间变量。
在MATLAB中实现和使用这种“单例注册表”的正确方法是什么?
应该注意的是,单例类包含一些在向列表中添加元素时调用的逻辑,用于以正确顺序正确销毁对象的逻辑以及迭代对象列表的其他方法。因此,不能使用“正常”containers.Map
。
这可能是你正在寻找的:
classdef (Abstract) Registry % < handle <-- optional
methods (Access = public, Static = true)
function addElement(elementName, element)
Registry.accessRegistry('set', elementName, element );
end
function element = get(elementName)
element = Registry.accessRegistry('get', elementName);
end
function reset()
Registry.accessRegistry('reset');
end
end
methods (Access = private, Static = true)
function varargout = accessRegistry(action, fieldName, fieldValue)
% throws MATLAB:Containers:Map:NoKey
persistent elem;
%% Initialize registry:
if ~isa(elem, 'containers.Map') % meaning elem == []
elem = containers.Map;
end
%% Process action:
switch action
case 'set'
elem(fieldName) = fieldValue;
case 'get'
varargout{1} = elem(fieldName);
case 'reset'
elem = containers.Map;
end
end
end
end
由于MATLAB doesn't support static
properties,必须采用各种workarounds,可能涉及methods
和persistent
变量,就像我的答案中的情况一样。
以下是上述用法示例:
Registry.addElement('name1', gobjects(1));
Registry.addElement('name2', cell(1) ); % assign heterogeneous types
Registry.get('name1')
ans =
GraphicsPlaceholder with no properties.
Registry.get('name1').get % dot-access the output w/o intermediate assignment
struct with no fields.
Registry.get('name2'){1} % {}-access the output w/o intermediate assignment
ans =
[]
Registry.get('name3') % request an invalid value
Error using containers.Map/subsref
The specified key is not present in this container.
Error in Registry/accessRegistry (line 31)
varargout{1} = elem(fieldName);
Error in Registry.get (line 10)
element = Registry.accessRegistry('get', elementName);