2008-09-18

Eclipse Template: Singleton Pattern

Are you writing your Java classes as Singletons quite often? Use this Eclipse template and make any class a singleton in two seconds:

Setup

Go to Window -> Preferences -> Java -> Editor -> Templates. Create New:



Code for copy paste:
private static final ${enclosing_type} instance = new ${enclosing_type}();
private ${enclosing_type}() {}
public static ${enclosing_type} getInstance() {
    return instance;
}


Action

Type "single" or "singleton", hit Content Assist shortcut key (ctrl+space by default), then enter:



And there you go - a singleton in two seconds (actual time may vary on your typing and CPU speed).



You may want to use a different Singleton implementation. Check out Java Singleton: The Proper Way for a good example.

3 comments:

  1. eclipse templates makes a lot of things easy :)

    ReplyDelete
  2. Thank you for the tip. Very helpful.

    ReplyDelete
  3. Love it.
    Just googled for something like this and this blog came nearly on top.

    ReplyDelete

Spam comments (i.e. ones that contain links to web development services) will be reported along with user profiles!

Note: only a member of this blog may post a comment.