Re: single class instance question

Steve Johnson <[email protected]>
Newsgroups gmane.comp.windows.off-topic
Message-ID <[email protected]>
Make the constructor private and expose a static factory method, say
"CreateInstance".  Code the factory method to allow only one instance.

--
Steve Johnson

On Sat, Jun 19, 2010 at 6:49 PM, John Smith <[email protected]> wrote:

>
>
> Hi All,
>   Other than through tight source code control, Is there anyway to keep
> multiple instances of a specific class from being created in the same
> program? For example, say I have a class MyClass and somewhere else in the
> code I have an instance of MyClass called MyInstance. Is there anyway to
> keep additional instances of MyClass from being created once MyInstance has
> been created? This is only a potential problem because multiple programmers
> will be working on this particular project.
>
>   I can hear the question now, "Why are multiple instances of the class a
> problem?" The reason is because the class contains functionality that I
> don't want conflicting with another instance of itself. Any ideas on how to
> prevent this?
>
>   I managed to increment an 'instance' counter that increments by 1 each
> time the class constructor is called and inside the constructor I check to
> see if the counter == 1 or not and if not, then I branch to an 'else' block
> and call the class destructor on the second (or subsequent) instance. The
> problem is that I can still call functions in the class through the second
> instance, even after the destructor has been called on it.
>
>
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.