Friday, February 01, 2008

Singleton (Creational)

Name : Singleton
Comment : Probably the best known (atleast if you go by answers you get in interviews to the question 'Patterns you have used') of the design patterns and probably one of the text book cases of people ignoring understand the context and understand the consequences when it comes to this pattern
Context : Need only 1(or a fixed or controllable number of instances) (e.g. memory consumption , or heavy initialization like reading a file,a requirement - there is only one Neo, a pre java 1.5 enum such that == can be used )
Examples : Single Instance (java.awt.Toolkit, Inspector)
Consequences :
a) Controlled access to state
b) Permits a variable number of instances (e.g. access to any object pool)!
c) Watch out for real world multiple managed servers, clusters etc(older versions of Expresso framework used an in memory primary key generator as an incremented singleton - no use in a cluster. Real world naive code that uses a timestamp plus ip address as unique key through a singleton)
d) Watch out for synchronized access for loading the singleton, thread safety, shared state.
e) Watch out for serializable (might break singletoness if you dont follow effective java)
f) Watch out for static block errors during initialization(if initialising eagerly). Will cause NoClassDefFoundErrors.
g) Watch out for being unable to reset a singleton (e.g. a singleton that reads a file and stores it.If your not careful , changing the file needs a bounce of the server)
h) Watch out for singletonitis. i.e. Making classes singleton even when there is no shared state, no performance or initialisation penalty.
i) Watch out for problems testing the singleton

With all the Watch out's is this pattern worth the trouble? read the context!

No comments: