Thursday, February 9, 2012

the Singleton pattern reviewed

Interesting approach to the singleton pattern in Joshua Bloch's book 'Effective Java' 2nd edition.


public enum Singleton {
    INSTANCE;
}

This simple idiom solves a lot of non-trivial problems, as synchronization or serialization. I do really like this approach -I had never thought about this option. 


What about you?



2 comments:

  1. I think that there is a remaining problem: change the class with some subclass without affecting the clients. (some programmers say that this is one of the reasons, among others, why Singletons are normal classes, instead of all-members-static classes).

    In the traditional singleton, this could be done changing the body of the getInstance() method.

    However, I think this is a minor problem. Good idiom!

    ReplyDelete
  2. Hi Lipido,

    well, you always have this problem implementing the singleton pattern as you cannot extend the static method that returns the singleton instance.

    You could always return from the superclass a subclass instance, but that would break the whole encapsulation property.

    Have a good one!

    ReplyDelete

State machines in JS

You can read in previous blog posts the reasoning behind state machines: they simplify and unify the way we define states and transitions i...