Singleton --- almost

H

HK

Hi,

once in a while I have a class which is a singleton --- almost. It
means
there is a default object which does not change its inner state
at all and can be used in nearly all cases. Only for special needs
a differently parameterized object is necessary.

What I typically do, looks like this:

public class TheClass {

// provide default object to be used most of the time
public static final TheClass THECLASS = new
TheClass(some_default_param);

public TheClass(SomeParamType param) {
// create special purpose object.
}
}

The thing which annoys me is that to use the default object
I end up writing TheClass.THECLASS all over the place, which
I find a bit too verbose.

With Java 5 I can import the static object, but I wonder if
there is a more clever solution --- less verbose --- for earlier
Java versions.

Harald.
 
A

Andrew McDonagh

HK said:
Hi,

once in a while I have a class which is a singleton --- almost. It
means
there is a default object which does not change its inner state
at all and can be used in nearly all cases. Only for special needs
a differently parameterized object is necessary.

What I typically do, looks like this:

public class TheClass {

// provide default object to be used most of the time
public static final TheClass THECLASS = new
TheClass(some_default_param);

public TheClass(SomeParamType param) {
// create special purpose object.
}
}

The thing which annoys me is that to use the default object
I end up writing TheClass.THECLASS all over the place, which
I find a bit too verbose.

With Java 5 I can import the static object, but I wonder if
there is a more clever solution --- less verbose --- for earlier
Java versions.

Harald.

A better solution is to not use a singleton in the first place.
JustCreateOne instead of a singleton.

Singletons after all are just global data & behavior wrapped in a class.

See....


http://www.google.co.uk/search?hl=en&q=singletons+are+bad&spell=1

if you must do the above, then the standard static method is 'getInstance()'

HTH
Andrew
 
R

Ryan Stewart

Andrew McDonagh said:
A better solution is to not use a singleton in the first place. JustCreateOne
instead of a singleton.

Singletons after all are just global data & behavior wrapped in a class.

See....


http://www.google.co.uk/search?hl=en&q=singletons+are+bad&spell=1
Even from this article:
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx

and a couple others, I still don't see what it is about singletons that
supposedly makes unit testing difficult and leads to more tightly coupled code.
I'm trying to figure this stuff out since a design we are creating at work makes
extensive use of singletons as a sort of "service layer". One of the things that
led us to use singletons was to make for *easier* unit testing, as we would have
a number of static methods, and we're thinking of using interfaces for most
things to allow for easier mock object substitution in testing. What other
opinions are out there on singletons?
 
J

Jesper Nordenberg

Ryan Stewart said:
Even from this article:
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx

and a couple others, I still don't see what it is about singletons that
supposedly makes unit testing difficult and leads to more tightly coupled code.
I'm trying to figure this stuff out since a design we are creating at work makes
extensive use of singletons as a sort of "service layer". One of the things that
led us to use singletons was to make for *easier* unit testing, as we would have
a number of static methods, and we're thinking of using interfaces for most
things to allow for easier mock object substitution in testing. What other
opinions are out there on singletons?

You just mentioned one problem with singletons in your post; it's hard
to create a mock object that replaces a singleton object. Basicly,
when you use a singleton in a class you're coupling the class to a
specific implementation. A more flexible solution is to send an
implementation of an interface as argument to the class constructor.

Another problem I can see with singletons is that can you really be
100% sure that you will only have one instance of the singleton class?
For example, if you create an application with one frame you might
argue that you can use a singleton for the data model, but if you
later want to open a new frame with other data you have a serious
problem.

Previously I've used singletons quite frequently in my code, but
nowadays I only use them when I want to prevent someone from creating
multiple instances of a class (and never for managers etc.).

/Jesper Nordenberg
 
C

Chris Uppal

Ryan said:
What other opinions are out there on
singletons?

I think the opposition to Singleton is in general overstated, and based on an
over-tight interpretation of what the pattern actually is.

As generally stated Singleton does two things; one is to ensure that you know
where to find an important object, the second is to ensure that no other
instances of that class are created.

As far as I can see, all the opposition to Singleton (that makes any sense to
me anyway) is focussing on the latter property. Yet (IMO) that property is
almost completely irrelevant to most applications of the design pattern. If
you drop that restriction, then you have a pattern which is (for all reasonable
purposes) identical to "classic" Singleton, and which is blameless. I suppose
you could give it a different name, like "Distinguished Instance", but I don't
bother, and just call it Singleton.

As an implementation artefact, Singleton can lead to unnecessary coupling /if/
you make the class be the "manager" of the Singleton (sorry, "Distinguished
Instance"). /All/ class names lead to coupling, and all static methods lead to
coupling. A static method getInstance() is certainly introducing coupling into
the system, but that's not a properly of the Singleton design pattern, but a
consequence of choosing a particular way to implement it. If you design your
system so that -- for instance -- there is a "registry" of singletons that code
queries at runtime (rather than invoking static methods of implementation
classes), then the pattern does not lead to coupling. Of course, that is also
more messing around, so it's worth considering YAGNI and whether it'd be better
just living with a bit of extra coupling unless/until you need to decouple.

-- chris
 
R

Ryan Stewart

Jesper said:
"Ryan Stewart" <[email protected]> wrote in message

You just mentioned one problem with singletons in your post; it's hard
to create a mock object that replaces a singleton object.
Why is it any harder than creating a mock for any other object? An
object is an object. If the singleton implements an interface, then you
can create a mock object that implements the interface.
Basicly,
when you use a singleton in a class you're coupling the class to a
specific implementation.
I think you mean when you use a class name in a class, which occurs any
time you use a static method for something, and that is not how we plan
to get instances of the singleton.
A more flexible solution is to send an
implementation of an interface as argument to the class constructor.
As I said before, our singletons will implement an interface. Therefore
there will not be any flexibility restriction. Also, some classes that
will use these objects are third party and not instantiated by our
code, so we can't modify constructors. We are leaning toward injection:
classes contain a reference of the interface type and a setter to
insert an instance when needed.
Another problem I can see with singletons is that can you really be
100% sure that you will only have one instance of the singleton class?
For example, if you create an application with one frame you might
argue that you can use a singleton for the data model, but if you
later want to open a new frame with other data you have a serious
problem.
I'm not working with frames. But the situation you describe seems like
a bad place for a singleton in the first place, partly because it could
quite easily lead to the problem you mentioned. I see no reason to make
a "data model" type object a singleton. In fact, it seems completely
contrary to the general idea of a data model.
Previously I've used singletons quite frequently in my code, but
nowadays I only use them when I want to prevent someone from creating
multiple instances of a class (and never for managers etc.).
Define "managers"?
 
J

John C. Bollinger

Ryan said:
Even from this article:
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx

and a couple others, I still don't see what it is about singletons that
supposedly makes unit testing difficult and leads to more tightly coupled code.
I'm trying to figure this stuff out since a design we are creating at work makes
extensive use of singletons as a sort of "service layer". One of the things that
led us to use singletons was to make for *easier* unit testing, as we would have
a number of static methods, and we're thinking of using interfaces for most
things to allow for easier mock object substitution in testing. What other
opinions are out there on singletons?

I think Singleton is the single most misused design pattern in the
current lexicon.

I have at times heard or received comments that a class should be made a
Singleton because only one instance is needed: THIS IS TOTALLY WRONG.
In the first place, whether more than one instance might be *needed* is
a completely different question from whether more than one instance
should be *allowed*. Secondarily, I have little faith in assertions
such as I described actually being accurate. It is my opinion that they
tend to arise when people look for design patterns to apply, instead of
trying to judge which design patterns are appropriate (perhaps a subtle
distinction). The structure of the Singleton pattern is relatively easy
to understand, which makes the pattern low-hanging fruit for pattern
seekers.

I am in agreement with other respondents that it is frequently best to
simply create only those objects you need, without applying special
structure to your classes. It may be useful to have a registry of
particular objects used by your application; with a Singleton, the class
itself serves as such a registry, but there is no special need for that.
In fact, unless there is a particular need that the same object be
used everywhere throughout the application, I would do away with any
central registry.
 
A

Andrew McDonagh

Ryan said:
Even from this article:
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx

and a couple others, I still don't see what it is about singletons that
supposedly makes unit testing difficult and leads to more tightly coupled code.
I'm trying to figure this stuff out since a design we are creating at work makes
extensive use of singletons as a sort of "service layer". One of the things that
led us to use singletons was to make for *easier* unit testing, as we would have
a number of static methods, and we're thinking of using interfaces for most
things to allow for easier mock object substitution in testing. What other
opinions are out there on singletons?

Most of the other replies have stated the various problems associated
with general singleton usage.
John Bollinger's posting is very good about the typical problems people
get into with them and why.

If ease of access to the single instance is truly required, then the
singleton Registry can help a lot.

As for the easiness of unittesting...

Your brief description of how you are implementing your singletons
sounds slight different to what the 'general' implementation is, e.g.:

public class MySingleton {

public MySingleton getInstance() {
return theInstance;
}

private static MySingleton theInstance = new MySingleton;
}

One problem not yet mentioned with singletons is that it prevents future
derived classes.

The static method is bound to the MySingleton class and can't be over
ridden to return a DerivedMySingleton. So substitutability is lost.

However, I'm intrigued by your mention of returning interfaces.

Does this mean your typical implementation is more like...

public interface MySingleton {
....
}

public class SingletonContainer {

public MySingleton getInstance() {
return theInstance;
}

private MySingleton theInstance = new MyFirstSingletonImpl;
}


I take it then that the SingletonContainer has some means for the unit
tests to substitute the object thats returned, like...

public class SingletonContainer {

public MySingleton getInstance() {
return theInstance;
}

// package visibility
void setInstanceForTest(MySingleton testSingleton) {
theInstance = testSingleton;
}

private MySingleton theInstance = new MyFirstSingletonImpl;
}


If this is the approach you are going for, then I'd say that you are one
step away from using an abstract factory to control the creation of
MySingleton derived instances, and its the factory that is the
singleton, not the object it returns.

IMO this is a better approach that using a straight forward singleton,
as it solves a lot of problems associated with typical singletons and
allows substitutability. It also means that the Single Responsibility
principle is maintained. Now the abstract factory may also need to be a
singleton and usually are.

Andrew
 
A

Andrew McDonagh

Ryan said:
Even from this article:
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx

and a couple others, I still don't see what it is about singletons that
supposedly makes unit testing difficult and leads to more tightly coupled code.
I'm trying to figure this stuff out since a design we are creating at work makes
extensive use of singletons as a sort of "service layer". One of the things that
led us to use singletons was to make for *easier* unit testing, as we would have
a number of static methods, and we're thinking of using interfaces for most
things to allow for easier mock object substitution in testing. What other
opinions are out there on singletons?

One aspect that usually rears its ugly head when using singletons and
unit tests, is the ability (or lack of) to run each unit test with new
instances of objects. Making sure the objects are not already polluted
with state and data from other tests is essential. Every unit test
should be able to be run independently.

When using singletons, this usually means you will need some kind of
reset() method on the singleton to clear out its state.

public class Broadcaster {

public static Broadcaster getInstance() {
return theInstance;
}

public addListener(BoardcasterListener aListener) {
listeners.add(aListener);
}

public void sendMessage(String message) {
for (i = 0; i < listeners.size(); i++ {
BoardcasterListener listener = (BroadcasterListener)
listeners.get(i);
listener.hereIsMessage(message);
}
}

/** for test means only */
void reset() {
listeners = new ArrayList();
}

private List listeners = new ArrayList();

private static Broadcaster theInstance = new Broadcaster();
}


Alternatively, each unit test must know how to manually reset the
singleton, by calling existing methods that will have the same effect as
an automatic reset(). However, we are then into the realms of breaking
encapsulation as the unit tests are now tightly coupled to the
implementation of the class. This may or may not be a problem - like
everything in life - it depends.
 
D

Daniel Dyer

One aspect that usually rears its ugly head when using singletons and
unit tests, is the ability (or lack of) to run each unit test with new
instances of objects. Making sure the objects are not already polluted
with state and data from other tests is essential. Every unit test
should be able to be run independently.

One possible work-around is that you could perform some ClassLoader
jiggery-pokery to get around that and effectively give each test it's own
"singleton" instance. Which raises the issue that a singleton in Java is
not really a singleton at all.

Dan.
 
A

Andrew McDonagh

Daniel said:
One possible work-around is that you could perform some ClassLoader
jiggery-pokery to get around that and effectively give each test it's
own "singleton" instance. Which raises the issue that a singleton in
Java is not really a singleton at all.

Dan.

Agreed, but it raises the issue that a singleton is not the pattern to
use in the first place ;-)

Don't get me wrong, I have no real axe to grind as to whether singletons
are bad and should be destroyed. Its more the mis-use of them. As John
says, they are the low hung fruit which the inexperienced (in patterns
at least) developers tend to pick up first and use often.

There are times when singletons are the correct pattern to use, but its
so rare that I tend to consider singletons to be an anti-pattern.
 
J

Jesper Nordenberg

Ryan Stewart said:
Why is it any harder than creating a mock for any other object? An
object is an object. If the singleton implements an interface, then you
can create a mock object that implements the interface.

Sure, you can do that, but how do you replace the singleton instance
with the mock object in your test case? Having a public set method
sounds like a very bad idea to me. And what if you want to use
different mock objects for the singleton at the same time (for
example, if you have multiple classes accessing the singleton)?
As I said before, our singletons will implement an interface. Therefore
there will not be any flexibility restriction. Also, some classes that
will use these objects are third party and not instantiated by our
code, so we can't modify constructors. We are leaning toward injection:
classes contain a reference of the interface type and a setter to
insert an instance when needed.

A public setter for a singleton? Sounds like bad design to me.
I'm not working with frames. But the situation you describe seems like
a bad place for a singleton in the first place, partly because it could
quite easily lead to the problem you mentioned. I see no reason to make
a "data model" type object a singleton. In fact, it seems completely
contrary to the general idea of a data model.

I was just providing an example of how singletons are often misused.
Can you provide an example on how you use singletons in your project?
Define "managers"?

Managers are typically classes that handle a number of related objects
(for example you might have a manager for connections, clients etc.).
It's common that people create singleton classes for these, but I
would argue that it's almost always bad design and leads to many
problems later.

/Jesper Nordenberg
 
R

Ryan Stewart

John C. Bollinger said:
I think Singleton is the single most misused design pattern in the current
lexicon.

I have at times heard or received comments that a class should be made a
Singleton because only one instance is needed: THIS IS TOTALLY WRONG. In the
first place, whether more than one instance might be *needed* is a completely
different question from whether more than one instance should be *allowed*.
Secondarily, I have little faith in assertions such as I described actually
being accurate. It is my opinion that they tend to arise when people look for
design patterns to apply, instead of trying to judge which design patterns are
appropriate (perhaps a subtle distinction). The structure of the Singleton
pattern is relatively easy to understand, which makes the pattern low-hanging
fruit for pattern seekers.

I am in agreement with other respondents that it is frequently best to simply
create only those objects you need, without applying special structure to your
classes. It may be useful to have a registry of particular objects used by
your application; with a Singleton, the class itself serves as such a
registry, but there is no special need for that. In fact, unless there is a
particular need that the same object be used everywhere throughout the
application, I would do away with any central registry.
What about a situation where you frequently use a stateless object to service
other objects? If the service object is not a singleton, hundreds or thousands
of them might be created and discarded in a short time. As a singleton, only the
one instance is ever created, and this is perfectly sufficient. Would you
consider this a valid reason to use the pattern?
 
R

Ryan Stewart

Andrew McDonagh said:
Most of the other replies have stated the various problems associated with
general singleton usage.
John Bollinger's posting is very good about the typical problems people get
into with them and why.

If ease of access to the single instance is truly required, then the singleton
Registry can help a lot.
As I mentioned in my reply to John's post, it's not so much a problem of ease of
access to an instance as to enforcing a single instance instead of creating
thousands of them when one will do.
As for the easiness of unittesting...

Your brief description of how you are implementing your singletons sounds
slight different to what the 'general' implementation is, e.g.: [...]
One problem not yet mentioned with singletons is that it prevents future
derived classes.

The static method is bound to the MySingleton class and can't be over ridden
to return a DerivedMySingleton. So substitutability is lost.

However, I'm intrigued by your mention of returning interfaces.

Does this mean your typical implementation is more like...

public interface MySingleton {
...
}

public class SingletonContainer {

public MySingleton getInstance() {
return theInstance;
}

private MySingleton theInstance = new MyFirstSingletonImpl;
}
Not necessarily. The singleton implements an interface, and any use of the
singleton is done through that interface, as above. Therefore a mock singleton
to be used in unit testing will simply implement that interface. The static
getInstance method is not intended to be used in normal code. Instances will be
injected, a la Spring framework, to reduce coupling. So for testing, we switch
everything that wants a MySingleton implementation to the mock implementation.
For production, we switch it to the real implementation.
I take it then that the SingletonContainer has some means for the unit tests
to substitute the object thats returned, like...

public class SingletonContainer {

public MySingleton getInstance() {
return theInstance;
}

// package visibility
void setInstanceForTest(MySingleton testSingleton) {
theInstance = testSingleton;
}

private MySingleton theInstance = new MyFirstSingletonImpl;
}


If this is the approach you are going for, then I'd say that you are one step
away from using an abstract factory to control the creation of MySingleton
derived instances, and its the factory that is the singleton, not the object
it returns.

IMO this is a better approach that using a straight forward singleton, as it
solves a lot of problems associated with typical singletons and allows
substitutability. It also means that the Single Responsibility principle is
maintained. Now the abstract factory may also need to be a singleton and
usually are.
I've considered the factory idea. The question remains, though, whether making
something a singleton to prevent thousands of unnecessary instances is a valid
reason for using the pattern. Would you use the factory to limit the number of
instances of an object that are handed out, i.e. making a singleton without
applying the pattern to a class?
 
A

Andrew McDonagh

Ryan said:
What about a situation where you frequently use a stateless object to service
other objects? If the service object is not a singleton, hundreds or thousands
of them might be created and discarded in a short time. As a singleton, only the
one instance is ever created, and this is perfectly sufficient. Would you
consider this a valid reason to use the pattern?

I would start out with the hundreds or thousands of stateless service
objects. Then when a profiler proved they were a performance bottleneck,
I'd change the design. In this case, I would guess that a Flyweight
pattern may be more appropriate. IOW I'd create just one service object
and allow it to contain state from a given context, for a given time.

For example, we can look at how JTable renderers work.

we could create a singleton renderer object and assign it to a column,
or we could simple create one instance and assign it - either way, when
called, the single renderer is passed the context info to enable it to
decide how to renderer the cell.

We wouldn't create an instance of the renderer for each cell.
 
R

Ryan Stewart

Jesper Nordenberg said:
Sure, you can do that, but how do you replace the singleton instance
with the mock object in your test case? Having a public set method
sounds like a very bad idea to me. And what if you want to use
different mock objects for the singleton at the same time (for
example, if you have multiple classes accessing the singleton)?
Use a factory to create instances, give the mock object a factory method and use
that, use an outside controller to instantiate a mock object and place it in
your test... Just thoughts.
A public setter for a singleton? Sounds like bad design to me.
The setter is not in the singleton. That would make it stateful and a Very Bad
Thing. The setter is on certain classes that need some implmentation of a given
interface. Which implementation or how it is retrieved doesn't matter one bit.
I was just providing an example of how singletons are often misused.
Can you provide an example on how you use singletons in your project?
Pseudo Struts action:
CreateUserAction {
private UserService userService;

public ActionForward execute(...) {
User user = userService.create(properties);
user.doSomething();
}

public void setUserService(UserService userService) {
this.userService = userService;
}
}

The UserService is a singleton.
 
J

Jesper Nordenberg

Ryan Stewart said:
Pseudo Struts action:
CreateUserAction {
private UserService userService;

public ActionForward execute(...) {
User user = userService.create(properties);
user.doSomething();
}

public void setUserService(UserService userService) {
this.userService = userService;
}
}

The UserService is a singleton.

Ok, but that code has nothing to do with singletons. You could use any
implementation of UserService, not necessarily a singleton instance.
Usually one gets the singleton instance through a static method in the
singleton class, which means you wouldn't store a reference to the
instance where it's used like in your example. There is no need to use
a singleton in your example.

/Jesper Nordenberg
 
J

John C. Bollinger

Ryan said:
What about a situation where you frequently use a stateless object to service
other objects? If the service object is not a singleton, hundreds or thousands
of them might be created and discarded in a short time. As a singleton, only the
one instance is ever created, and this is perfectly sufficient. Would you
consider this a valid reason to use the pattern?

Absolutely not. This is one of those cases where perhaps (perhaps!)
only one instance is needed, but the class has no *inherent* need to
prevent multiple instances from being created. It is up to the other
objects using the class to adopt an effective usage strategy. If
creation and release of large numbers of instances were an actual
problem then it would in most cases be very easy for the application to
hold and reuse one or more instances. This sort of thing then starts
sounding like the Strategy pattern.
 
J

John C. Bollinger

Ryan said:
As I mentioned in my reply to John's post, it's not so much a problem of ease of
access to an instance as to enforcing a single instance instead of creating
thousands of them when one will do.

Whether the registry is in the proposed Singleton class or outside it,
having one (which need not be explicit) addresses both problems.
They're closely related anyway, for if an object already has ready
access to an instance it may use, then it doesn't need to create a new one.
I've considered the factory idea. The question remains, though, whether making
something a singleton to prevent thousands of unnecessary instances is a valid
reason for using the pattern.

No. The class should accurately abstract the thing it represents, and
there are very few cases where a good abstraction has Singleton nature.
The mode of use of a class and its instances is in most cases a
question separate from the class itself -- if you want to manage that
then you may have use for an additional class to assist you. That's
where Andrew's suggestion of a Factory comes in, or my suggestion of a
registry. (A Factory is a generalization of the registry idea.)
Would you use the factory to limit the number of
instances of an object that are handed out, i.e. making a singleton without
applying the pattern to a class?

I don't know about Andrew, but I might do so if I found the number of
instances to be a problem. However,
(1) I would be more likely to try to handle the situation by caching one
or a few instances where they were needed, and / or by passing them as
method arguments, than to pursue a design where a Factory would be
useful in limiting the number of instances; and
(2) Ensuring that there is only one instance is not at all the same
thing as applying the Singleton pattern. This is exactly where many of
us started in our responses to your original message.
 
A

Andrew McDonagh

John said:
Whether the registry is in the proposed Singleton class or outside it,
having one (which need not be explicit) addresses both problems. They're
closely related anyway, for if an object already has ready access to an
instance it may use, then it doesn't need to create a new one.



No. The class should accurately abstract the thing it represents, and
there are very few cases where a good abstraction has Singleton nature.
The mode of use of a class and its instances is in most cases a
question separate from the class itself -- if you want to manage that
then you may have use for an additional class to assist you. That's
where Andrew's suggestion of a Factory comes in, or my suggestion of a
registry. (A Factory is a generalization of the registry idea.)



I don't know about Andrew, but I might do so if I found the number of
instances to be a problem. However,
(1) I would be more likely to try to handle the situation by caching one
or a few instances where they were needed, and / or by passing them as
method arguments, than to pursue a design where a Factory would be
useful in limiting the number of instances; and
(2) Ensuring that there is only one instance is not at all the same
thing as applying the Singleton pattern. This is exactly where many of
us started in our responses to your original message.

John,

You have nicely summed up my preferences there.

A good white paper by J. B. Rainsberger on singletons can be found ...

http://www-106.ibm.com/developerworks/webservices/library/co-single.html
 

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,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top