Archive for October, 2008

Sometimes HashMaps are enough, part three

This part will be a short one because I have to pack for my vacation. Yes, I will leave this cold and miserable weather, heading south to fill up my energy again (I am running on solar power).

Last time we switched from a static approach to an instance based one and introduced a register-method to allow adding Singletons from everywhere. There are several issues with this approach:

  • doesn’t support lazy initialization, so far only eager initialization was done
  • sometimes not all necessary information is available at register time to actually create the Singleton instance
  • maybe you want to track, creation, requesting, and so forth of the Singleton.

Sounds complicated and scary? It isn’t, delegation is our friend again. Another way would be the observer (listener) pattern to address the above mentioned issues, however, delegation is more elegant and appropriate for this task.

Continue Reading »

heli's blog heli 07 Oct 2008 No Comments

Sometimes HashMaps are enough, part two

The previous post shows how to implement a very simple and static approach to create Singletons using a static “Singleton” class. Now it is time to refactor our solution and make it more flexible.

First, I want to get rid of the static context. Static is very simple but also restrictive and we want and need flexibility later on. So instead of using static variables the get-method should delegate to the real implementation of the Singleton. How does this change our code?

Continue Reading »

heli's blog heli 06 Oct 2008 No Comments

Sometimes HashMaps are enough, part one

I guess we have all heard about how bad static Singletons are and how Dependency Injection (DI) helps to make our application flexible beyond crazy. One common thing to do with DI is creating and using Singletons. I have been working a lot with DI frameworks in the past, mostly Spring and Google Guice. Although both do a great job, I have been wondering lately if my applications always need this great flexibility. Don’t forget using them comes with a lot of baggage, e.g. new third party dependencies or XML configuration files. In a big project this is probably not a problem, but in small projects it is just unnecessary. Note, I don’t state that Spring or Guice are bad, but sometimes the whole DI stack is just too much for small projects.

Singletons are a great example. They are simple to understand and to use. Like I mentioned, DI frameworks are often used to provide a “better” way to create Singletons, sometimes as their main purpose. I will present a simple , yet powerful enough, solution creating and instrumenting Singletons using a plain HashMap with no dependencies and configuration files. Continue Reading »

heli's blog heli 02 Oct 2008 2 Comments