SIngleton implementation without persistent variables

조회 수: 33 (최근 30일)
Rohan
Rohan 2024년 8월 28일
댓글: Rohan 2024년 8월 29일
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.

답변 (1개)

Malay Agarwal
Malay Agarwal 2024년 8월 28일
편집: Malay Agarwal 2024년 8월 28일
Hi @Rohan,
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
obj =
singleton with properties: x: 5 y: "Hello"
obj1 = singleton.getInstance
obj1 =
singleton with properties: x: 5 y: "Hello"
% The two objects refer to the same handle
obj == obj1
ans = logical
1
% Changing non-constant properties in one object reflects changes in both the objects
obj.x = 2;
obj, obj1
obj =
singleton with properties: x: 2 y: "Hello"
obj1 =
singleton with properties: x: 2 y: "Hello"
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:
Hope this helps!

카테고리

Help CenterFile Exchange에서 Deployment, Integration, and Supported Hardware에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by