Products & Services Industries Academia Support User Community Company

Learn more about MATLAB   

Controlling the Number of Instances

Limiting Instances

You can limit the number of instances of a class that can exist at any one time. For example, a singleton class can have only one instance and provides a way to access this instance. You can create a singleton class using these elements:

Implementing a Singleton Class

The following skeletal class definition shows how you can approach the implementation of a class that allows you to create only one instance at a time:

classdef (Sealed) SingleInstance < handle
   methods (Access = private)
      function obj = SingleInstance
      end
   end
   methods (Static)
      function singleObj = getInstance
         persistent localObj
         if isempty(localObj) || ~isvalid(localObj)
            localObj = SingleInstance;
         end
         singleObj = localObj;
      end
   end
end

The getInstance static method returns a handle to the object created, which the class stores in a persistent variable. getInstance creates an instance only the first time called in a session or when the object becomes invalid. For example:

sobj = SingleInstance.getInstance
sobj = 
  SingleInstance handle with no properties.
  Methods, Events, Superclasses

As long as sobj exists as a valid handle, calling getInstance returns a handle to the same object. If you delete sobj, then calling getInstance creates an object and returns the handle.

delete(sobj)
isvalid(sobj)
ans =

     0
sobj = SingleInstance.getInstance;
isvalid(sobj)
ans =

     1
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS