singleton or member reference variable

I

ittium

Group,
I have two classes
Class A //At present only one instance of this class is needed
Class B //Multiple instances of this class will require single
instance of Class A.

I have two designs here

1. Define A as singleton so that wherever needed it can be accessed
using getInstance method. I want to avoid this design since my system
is multihreaded.
2. In Class B define a ** reference** member of type A. First
construct A and during construction of B pass instance of A. Here I
have flexibility of creating more instances of A in future.

Which approach is better. Is there anything better than this.
thanks
Ittium
 
V

Victor Bazarov

Group,
I have two classes
Class A //At present only one instance of this class is needed
Class B //Multiple instances of this class will require single
instance of Class A.

I have two designs here

1. Define A as singleton so that wherever needed it can be accessed
using getInstance method. I want to avoid this design since my system
is multihreaded.
2. In Class B define a ** reference** member of type A. First
construct A and during construction of B pass instance of A. Here I
have flexibility of creating more instances of A in future.

Which approach is better. Is there anything better than this.

Multithreadedness and singletons are not mutually exclusive. If you
need a single copy of A in every thread, you need the single copy. You
just implement it correctly, and you have a single copy working in all
threads. Certain operations would need to be protected, and that's what
you need in a multithreaded program... So, (1) is just as possible and
feasible as any other solution.

If you *need* the flexibility to switch from one instance of A to
several, then a singleton won't do. But you don't need to create a
pointer/reference to A in B, you could just have a "handle", which will
be served by a factory of A, and all A's methods should be accessed with
the help of that handle. Generally, an interface object to connect a B
and an A is better than a rigid type-specific link that a reference or a
pointer would provide.

Since so far you only stated a potential necessity to have more than one
instance of A shared among all B, that is the only requirement that
eliminates the singleton from the competition. BTW, if the same
instance of A can be shared by different B objects living in different
threads, you still need to protect certain operations, so
"multithreadedness" is the concern you can't ignore in either case.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,737
Latest member
Georgeengab

Latest Threads

Top