Controlling the Number of Instances

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:

  • A persistent variable to contain the instance
  • A sealed class (Sealed attribute set to true) to prevent subclassing
  • A private constructor (Access attribute set to private)
  • A static method to return the handle to the instance, if it exists, or to create the instance when needed.

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

You may also like...