Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

Control Number of Instances

Limit 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 must provide a way to access this instance. Create a singleton class using a:

  • Persistent variable to contain the instance

  • Sealed class to prevent subclassing (class Sealed attribute set to true)

  • Private constructor (method Access attribute set to private)

  • Static method to return the handle to the instance, if one exists, or to create the instance when needed.

Singleton Class Implementation

This 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, 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 with no properties

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

After deleting the object, you can create a new instance:

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

     1

See Also

More About

Was this topic helpful?