According to Matlab documentation, for creating the Singleton design pattern you need to set a persistent variable inside a static function for your singleton object instance, i.e.:
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
It is almost impossible to 'destruct' the singleton instance. I've tried clear SingleInstance, clear getInstance(), clear SingleInstance.getInstance(), clear functions, clear variables, and other combinations. The only way for the localObj persistent variable inside the getInstance() static method of the SingleInstance class is calling clear all.
I'm OK with calling clear all prior to calling my Matlab OO application. However, I'm using Matlab unit test infrastructure, and there are unit tests where I would like to test different ways of instantiating the singleton classes. However, for that I would need to call clear all, which would make the Matlab unit test infrastructure to stop working.
Does any one knows a way to cleaning persistent variable inside static methods of Matlab classes without calling clear all? Or, in other way, does any one knows how to implement the Singleton design pattern without using persitent variables? Or, at least, how calling clear all inside unit tests without breaking the unit test infrastructure?

