Single player tag interface

The "singleton-ness" of the class is an important aspect of using the class. However, it usually does not have an explicit status in the public API of the class. Yes, common method names such as getInstance () are usually used, but that's not exactly what I mean here.

A tag interface is an interface that contains no methods or data. An example of the Serializable tag interface .

Wouldn't it be helpful to define a tag interface for single numbers? It:

  • make them easy to identify in the project code base
  • be more explicit
  • provide a place to document how single trays should be handled. As one example, it can be mentioned that long-lived objects are fruitful sources of memory leaks, and that single points should never connect to short-lived objects.

It's a simple idea, but I've never seen it anywhere else.

+2


source to share


4 answers


You have entered a religious war here, but it seems to me that your idea has merit. As long as singletons exist, I think it would be nice if the compiler and JVM could enforce their atomic uniqueness.

The problem is that singletons have become controversial because they are prone to abuse. People who oppose their use point to a secret global state, hidden addictions and massive abuse.

None of these are, of course, fundamental to the concept of Singleton-ness, but that doesn't change the contradiction.



Your case here is not helped by using Serializable because, as Tom points out, it's self-contradictory. Of course, the fact that Serializable is considered a bug by some authors does not necessarily do this. I personally don't use it, but not because I think it's a bug in and of itself ... I just find there are better ways to save and get the state that better suits my users' needs.

There are, of course, other marker interfaces - Cloneable, EventThreadListener, and SingleThreadModel, if memory serves. You could get further if you used them as a model.

By the way, I think most authors refer to what you call the "tag interface" as the "marker interface". Not a big deal, but it might help you find other thoughts on the topic.

+2


source


This is an interesting idea, but I'm not sure how useful it is. Your third marker point is a good point.



The best argument might be "Why Singletons?" You will surely make life easier for Google Singleton Detector to find them and identify them for extermination. Their FAQ often expresses my opinion.

+1


source


Why not use a DI / IoC container and let it manage the lifetime of your objects? As you say, the lifetime of a class doesn't have to be reflected in its public interface.

0


source


I agree with TrueWill above about using the DI framework to handle object lifecycles. And using Guice will give you the Singleton annotation to tag the singlets. :)

0


source







All Articles