3/09/2015

IntelliJ Idea live templates: code for singletons

Say you have this class:

public class TerminalTitlebar {
    public void set(String title) {
        System.out.println("\033]0;" + title + "\007");
    }
}

...and you want to introduce code to change this into a singleton easily.

File -> Settings -> Live Templates -> Click + to create a new entry.

Enter i for abbreviation, "singleton instance" or something similar for description, and the code in the "Template text" field:

private static $CLASS_NAME$ instance;
public static $CLASS_NAME$ getInstance() {
    return instance == null ? instance = new $CLASS_NAME$() : instance;
}

Now click "Edit Variables", and change the Expression for CLASS_NAME to "className()", press OK

To tell IntelliJ to use the generated snippet in Java code, click "Change" in the "Applicable in" line, and select Java.

Now type the letter i (this was the abbreviation we used earlier) and press TAB and the magic happens:

public class TerminalTitlebar {
    private static TerminalTitlebar instance;

    public static TerminalTitlebar getInstance() {
        return instance == null ? instance = new TerminalTitlebar() : instance;
    }

    public void set(String title) {
        System.out.println("\033]0;" + title + "\007");
    }
}

Voila, you can use it in any class. Enjoy!


3 comments:

  1. This is absolutely brilliant. Thank you very much!

    ReplyDelete
  2. It's not thread-safe singleton

    ReplyDelete
    Replies
    1. The point of the article is to show how you can use Idea's live templates, nobody mentioned thread-safety... A quick google popped up http://stackoverflow.com/questions/16106260/thread-safe-singleton-class dealing with thread safety in singletons; I hope adapting the non-thread-safe example above will not pose a problem.

      Delete