单例注册表 class

Singleton registry class

我想创建一个单例 MATLAB class 作为全局注册表。注册表应该存储对象(来自 handle 的某个 class 派生的对象)以唯一名称寻址。我想方便地访问存储的classes的属性而不需要临时变量,例如:

Registry.instance().addElement('name1', NewObject(...));
Registry.instance().get('name1').Value
Registry.instance().get('name2').Value = 1;

读取返回的 class 的属性可以通过从 instance 中删除 () 来规避:

 >> Equipment.instance.get('name1').Value

但是,使用赋值似乎并不容易,因为如评论中所述,如果不分配给中间变量,则不能直接在函数的输出上使用点索引。

在 MATLAB 中实现和使用这样的 "singleton registry" 的正确方法是什么?

需要注意的是,单例 class 包含一些在向列表中添加元素时调用的逻辑、以正确顺序正确销毁对象的逻辑以及遍历对象列表的其他方法。因此,无法使用 "normal" 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, one must resort to various workarounds,可能涉及 methodspersistent 变量,就像我的回答中的情况一样。

下面是上面的用法示例:

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);