SIngleton implementation without persistent variables
Mostrar comentarios más antiguos
Hi,
I have a handle class with a singleton implementation that uses persistent variables.
classdef MyHandler < handle
properties
...
...
...
end
methods(Access=protected)
function obj = MyHandler()
%Constructor logic
end
end
methods(Static)
function inst = instance()
persistent obj;
if isempty(obj)
obj = MyPackage.MyHandler();
end
inst = obj;
end
end
end
Is there a way to implement the same functionality without usage of persistent variables ? I am trying to generate C code from a system object that uses this handle class.
Respuestas (1)
Malay Agarwal
el 28 de Ag. de 2024
Editada: Malay Agarwal
el 28 de Ag. de 2024
You can create a singleton class without using persistent variables by defining the instance as a constant property. I have attached an example class to the answer. You can verify that the class indeed behaves like a singleton:
% Create two objects
obj = singleton.getInstance
obj1 = singleton.getInstance
% The two objects refer to the same handle
obj == obj1
% Changing non-constant properties in one object reflects changes in both the objects
obj.x = 2;
obj, obj1
If you right click the class file and click on "Check Code Generation Readiness", you'll see that the tool does not report any issues:

Please refer to the following resources for more information:
- Constant properties documentation - https://www.mathworks.com/help/releases/R2022b/matlab/matlab_oop/properties-with-constant-values.html.
- Guidelines to make code generation work for classes - https://www.mathworks.com/help/releases/R2022b/simulink/ug/how-working-with-matlab-classes-is-different-for-code-generation.html.
Hope this helps!
2 comentarios
Rohan
el 29 de Ag. de 2024
Xiangrui Li
el 31 de Mayo de 2025
Neat implementation!
I do see one culprit. If I try to access the help information, like
help singleton % or
doc singleton
the instance will be initialized. This is can be easirly verified if you add
disp('Initializing')
in the actual constructor.
Any way to avoid this behavior?
Categorías
Más información sobre Simulink Functions en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!