Re: singleton or member reference variable
On 6/28/2011 7:52 AM, ittium wrote:
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
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.
I do not respond to top-posted replies, please don't ask