单例注册表类

时间:2018-08-28 09:10:19

标签: matlab oop dictionary singleton handle

我想创建一个单例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

1 个答案:

答案 0 :(得分:3)

这可能是您想要的:

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,可能涉及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); 
相关问题