Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Calling private constructor from a static method

Subject: Calling private constructor from a static method

From: Petr Posik

Date: 28 May, 2008 12:46:02

Message: 1 of 5

Hi, all.

Maybe a stupid question, but I did not find the answer in
the documentation.

How can I call a class constructor from a class static
method? This is needed e.g. when implementing the singleton
pattern, i.e. a class that exists only one in the system.
Usually, you have a static factory method that creates the
object if this is the forst call to factory, or returns the
previously created object, if this is subsequent call to
factory. (The reference/handle is stored in static class
property.)

I want to accomplish something like this:

classdef Singleton < handle
    properties (GetAccess=private,SetAccess=private)
        instance = [];
    end
    methods (Access=private)
        function obj = Singleton
        end
    end
    methods (Static)
        function inst = getInstance
            if isempty(instance),
                instance = Singleton();
            end
            inst = instance;
        end
    end
end

Can that be accomlished? Can I have a static property? How
do I call the Singleton constructor from the static method
getInstance?

Thanks a lot.

Petr Poš?k

Subject: Calling private constructor from a static method

From: Jozef

Date: 5 Jun, 2008 12:02:06

Message: 2 of 5

"Petr Posik" <posik@REMOVETHISlabe.felk.cvut.cz> wrote in
message <g1jk6a$jpa$1@fred.mathworks.com>...
> Hi, all.
>
> Maybe a stupid question, but I did not find the answer in
> the documentation.
>
> How can I call a class constructor from a class static
> method? This is needed e.g. when implementing the
singleton
> pattern, i.e. a class that exists only one in the system.
> Usually, you have a static factory method that creates the
> object if this is the forst call to factory, or returns
the
> previously created object, if this is subsequent call to
> factory. (The reference/handle is stored in static class
> property.)
>
> I want to accomplish something like this:
>
> classdef Singleton < handle
> properties (GetAccess=private,SetAccess=private)
> instance = [];
> end
> methods (Access=private)
> function obj = Singleton
> end
> end
> methods (Static)
> function inst = getInstance
> if isempty(instance),
> instance = Singleton();
> end
> inst = instance;
> end
> end
> end
>
> Can that be accomlished? Can I have a static property? How
> do I call the Singleton constructor from the static method
> getInstance?
>
> Thanks a lot.
>
> Petr Poš?k


Hallo,

did you find out something new? I have the same Problem. I
would like to implement Singelton Pattern but there is no
way to declare static members, as well as no possibility to
call object contructor mehtod from class static method.

Thanks
Joe

Subject: Calling private constructor from a static method

From: Petr Posik

Date: 9 Jun, 2008 09:00:07

Message: 3 of 5

"Jozef " <jozef.kohut@gmx.at> wrote in message
<g28kju$a1l$1@fred.mathworks.com>...
> Hallo,
>
> did you find out something new? I have the same Problem. I
> would like to implement Singelton Pattern but there is no
> way to declare static members, as well as no possibility to
> call object contructor mehtod from class static method.
>
> Thanks
> Joe

Hi, Jozef.

Since I did not find a way how to call private constructor
from a static method, I realized that calling the
constructor is the only way of creating an object (pls,
correct me someone if I am wrong). For the singleton
pattern, the constructor must somehow know if it has been
already called previously. That can be accomplished via a
persistent variable (see
http://www.mathworks.com/matlabcentral/newsreader/view_thread/169577#433256).

The persistent variable in the constructor will hold the
instance created for the first time. If it is empty it is
the first call and the newly created object is assigned to
the variable. If it is not empty, it is one of the
subsequent calls and the already created object is returned.
The persistent variable in the constructor will play the
role of the private static property holding the instance.

Hm, I am not quiet sure about the workings behind the scene
- if two handle objects created this way would than contain
a reference to the same object, but it seems to be a working
solution.

classdef Singleton < handle
    properties
        number = 0; % Just to show something...
    end
    methods
        function obj = Singleton
            persistent myobj;
            if isempty(myobj),
                disp('New instance');
                myobj = obj;
            else
                disp('Old instance');
                obj = myobj;
            end
        end
    end
end

Then try:

1> s = Singleton
2> t = Singleton
3> s.number = 1000;
4> t.number
(Should return 1000)
5> s == t
(Should return 1)

A small remark: the just mentioned beahvior can be certainly
accomplished by just using a handle classes. If you would be
able to ensure, that you call the Singleton constructor (s =
Singleton) only once, than you can easily assign the
references to that object by simply issueing the command t =
s. The behavior would be the same, the lines 1-5 would give
you the same results.

The reason why to create something like Singleton pattern is
to be able to create/get the one and only instance of that
object in any place of your code without knowing that
another part of your code has already created that instance.

Hope this helps.

Petr Posik

Subject: Calling private constructor from a static method

From: Rob Joy

Date: 12 Jun, 2008 07:02:01

Message: 4 of 5

"Petr Posik" <posik@REMOVETHISlabe.felk.cvut.cz> wrote in
message <g2iren$fe4$1@fred.mathworks.com>...
> "Jozef " <jozef.kohut@gmx.at> wrote in message
> <g28kju$a1l$1@fred.mathworks.com>...
> > Hallo,
> >
> > did you find out something new? I have the same
Problem. I
> > would like to implement Singelton Pattern but there is
no
> > way to declare static members, as well as no
possibility to
> > call object contructor mehtod from class static method.
> >
> > Thanks
> > Joe
>
> Hi, Jozef.
>
> Since I did not find a way how to call private constructor
> from a static method, I realized that calling the
> constructor is the only way of creating an object (pls,
> correct me someone if I am wrong). For the singleton
> pattern, the constructor must somehow know if it has been
> already called previously. That can be accomplished via a
> persistent variable (see
>
http://www.mathworks.com/matlabcentral/newsreader/view_threa
d/169577#433256).
>
> The persistent variable in the constructor will hold the
> instance created for the first time. If it is empty it is
> the first call and the newly created object is assigned to
> the variable. If it is not empty, it is one of the
> subsequent calls and the already created object is
returned.
> The persistent variable in the constructor will play the
> role of the private static property holding the instance.
>
> Hm, I am not quiet sure about the workings behind the
scene
> - if two handle objects created this way would than
contain
> a reference to the same object, but it seems to be a
working
> solution.
>
> classdef Singleton < handle
> properties
> number = 0; % Just to show something...
> end
> methods
> function obj = Singleton
> persistent myobj;
> if isempty(myobj),
> disp('New instance');
> myobj = obj;
> else
> disp('Old instance');
> obj = myobj;
> end
> end
> end
> end
>
> Then try:
>
> 1> s = Singleton
> 2> t = Singleton
> 3> s.number = 1000;
> 4> t.number
> (Should return 1000)
> 5> s == t
> (Should return 1)
>
> A small remark: the just mentioned beahvior can be
certainly
> accomplished by just using a handle classes. If you would
be
> able to ensure, that you call the Singleton constructor
(s =
> Singleton) only once, than you can easily assign the
> references to that object by simply issueing the command
t =
> s. The behavior would be the same, the lines 1-5 would
give
> you the same results.
>
> The reason why to create something like Singleton pattern
is
> to be able to create/get the one and only instance of that
> object in any place of your code without knowing that
> another part of your code has already created that
instance.
>
> Hope this helps.
>
> Petr Posik

Hi Petr,

your code looks relly good now. I made some changes. I
implemented static method "getInstance" and declared
constructor as private. I call constructor from static
method only if no one instance of the class exists. I think
his was your first approach. Additionally I tried to get
only the HANDLE of the singleton object stored in
persistent variable "myobj", but I didn't succeed. Do you
have some Idea?

Here is the changed code:

classdef cSingleton < handle
    properties
        number = 999; % Just to show something...
    end
    methods (Access = private)
        function obj = cSingleton
        end
    end
    methods (Access = public)
        function test(obj)
            disp('test function'); % for testing
        end
    end
    methods (Static)
        function inst = getInstance()
            persistent myobj;
            if isempty(myobj),
                disp('New instance');
                myobj = cSingleton;
                inst = myobj;
            else
                disp('Old instance');
                inst = myobj;
            end
        end
    end
end

Thanks Joe

Subject: Calling private constructor from a static method

From: Petr Posik

Date: 12 Jun, 2008 08:50:19

Message: 5 of 5

> >
> >
> Hi Petr,
>
> your code looks relly good now. I made some changes. I
> implemented static method "getInstance" and declared
> constructor as private. I call constructor from static
> method only if no one instance of the class exists. I think
> his was your first approach. Additionally I tried to get
> only the HANDLE of the singleton object stored in
> persistent variable "myobj", but I didn't succeed. Do you
> have some Idea?

I am not quite sure what exactly you mean. I tried your code
with a similar test as I did for my code.

0> s = cSingleton
(Cannot access method 'cSingleton' in class 'cSingleton'.
1> s = cSingleton.getInstance
2> t = cSingleton.getInstance
3> s.number = 500;
4> t.number
(Returned 500)
5> s == t
(Returned 1)

So, my conclusion is that it works. Both variables s and t
hold handles to the same cSingleton object. Do I miss something?

Regarding the comparison of my and your code for the
singleton pattern: there are basically 2 points of view.

1) The main characteristic of the singleton pattern is that
it is an object which can have only 1 existing instance in
the system. The implementation details are not important and
one should use the simplest solution that is offered by the
respective programming language.

2) Additionally to 1), since in many programming languages
the singleton pattern usually has private constructor,
static method getInstance, and static property holding this
instance, we should try to implement it this way in all
programming languages. For the programmers such a solution
will be more understandable.

Both solutions have their pros and cons. I tend to think
that the view 1) and thus my solution is better. I feel
somehow that if the Singleton pattern could be implemented
this way in Java and other languages, no need for static
method getInstance, no private constructor, etc. would
arise. Your solution IMHO exhibits unnecessary complexity.
But its only my opinion, no flame pls. >:-)

Regards,

Petr

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us