image thumbnail
from The Object of My Callback by Dimitri Shvorob
(object references with Matlab timers)

Widget
classdef Widget
    
   % ad hoc timer-composing, timer-referenced class used by CallbackDemo.m
 
    
   properties
       Color
       TimeCreated
       Timer
   end
        
   methods (Static)
       
       function[obj] = getInstance(color)
           persistent instances
           if isempty(instances)
              instances = CharKeyHashtable();
           end
               
           if instances.iskey(color)
              obj = instances.get(color);
           else    
              obj = Widget(color);
              instances.put(color,obj)
           end
       end 
 
   end  
        
   methods 
            
       function start(obj)             
           start(obj.Timer)
       end
       
       function stop(obj)
           stop(obj.Timer)
       end
       
       function delete(obj)
           delete(obj.Timer)
       end 
       
       function disp(obj)
           fprintf('I am a %s widget created at %s \n',obj.Color,datestr(obj.TimeCreated,13))
       end 
       
   end 
   
   methods (Access = private)
       
      function[obj] = Widget(color)           
           obj.Color = color;
           obj.TimeCreated = now;
           obj.Timer = timer('TimerFcn',sprintf('Widget.getInstance(''%s'').disp',color), ...
                             'Period',1,'ExecutionMode',...
                             'fixedRate','TasksToExecute',20);            
      end
      
   end
       
end

Contact us at files@mathworks.com