Friday, September 11, 2009

Creating a singleton using Eclipse Code Templates

In this post I'd like to demonstrate the Eclipse Code Template feature for implementing a singleton pattern.
The Singleton is a creational pattern of the set of Gang-of-Four Java Design patterns. It uses a single static variable (the singleton), a private constructor to prevent public instantiation and a public static getter method to retrieve the instance. For lazy instantiation, the singleton instance is not preinitialized, instead, the static getter method checks if the instance is null and instantiates a new instance on its first call. Lazy instantiation (as used in the following example) is not uncommon, though it may cause race conditions in multithreaded environments.
The Code Template feature is an extension to the code-completion functionality that is accessible by pressing Ctrl+Space. When the user types in code, he may hit Ctrl+Space to auto-complete, what he was typing. Eclipse proposes a set of options for completion, i.e. a Type, method of that type etc.
The Code Template feature might be known from typing in "sysout", pressing Ctrl+Space and Eclipse completes this to "System.out.println("");".
To add a new code template,
  1. open to Window -> Preferences
  2. navigate to Java -> Editor -> Templates.
  3. click on "New..."
  4. set the name of the new template to "singleton" (this is what you type into the editor)
  5. as pattern enter
     * static Singleton instance
    private static ${enclosing_type} instance;
     * Private constructor for singleton
    private ${enclosing_type}(){
     * Static getter method for retrieving the singleton instance
    public static ${enclosing_type} getInstance(){
      if(instance == null) {
        instance = new ${enclosing_type}();
      return instance;

The variable ${enclosing_type} resolves to the Class you are editing. From now on, it is possible to create the entire singleton pattern by just typing "singleton" and hitting Ctrl+Space - saving lots of keystrokes!

No comments: