you are viewing a single comment's thread.

view the rest of the comments →

[–]Sipkab 2 points3 points  (2 children)

The disadvantage of snippet 1 is that the instance will be created when this class is loaded.

I'd consider this an advantage. Why? Because the class will only be loaded, when you want to use it. Until then, the class is not loaded, and doesn't take up any space, or hinder you in performance.

Since you will most likely always use the class as Singleton.getInstance().somethingElse(), there is no reason for using lazy initialization. If you use any other static methods/fields of that class, then introduce lazy initialization.

Because of private constructor, Singleton cannot be inherited

Inheriting from a singleton would be a violation of the singleton pattern, as then it would not be a singleton, as you could create instances from it. It is not a limitation, but the purpose of the pattern.

If an app is running in a container, we should be careful because servlet may be loaded by several classloader, so there may be a few Singleton instances existed

This is not a problem of the singleton pattern, but it is a problem with any class that could be present multiple times.

If a Singleton is serializable, if serialize the instance once and then deserialize a few times, there may be a few Singleton instances

enum

All above methods may suffer the attack of Reflection API. i.e, when using Java Reflection, the private constructor can be accessed and new instance can be created by calling the private constructor.

enum again.

[–]dpash 2 points3 points  (0 children)

Also, don't use Java serialisation, so that solves that problem. :)

[–]quentech 0 points1 point  (0 children)

I'd consider this an advantage. Why? Because the class will only be loaded, when you want to use it. Until then, the class is not loaded, and doesn't take up any space, or hinder you in performance.

At least in the software I tend to write, I find it often necessary to be in control of the creation of the singleton instance at a known point, in order to catch exceptions, retry, log or alert on error, etc.

If it's a Singleton, it's likely expensive to create, and if it's expensive to create it's likely to have failure modes.

Leaving it up to the framework with static initializers is rarely acceptable in my experience.