Creating A Singleton Using Java


In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. While this concept is also sometimes generalized to restrict the instance to a specific number of objects, in most cases, I tend to have it instantiated only once and used by the entire system. A good use for this would be loading property values and retrieving the class that holds those properties. Here is a sample code for a singleton class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MailProperties {
 
  private static MailProperties _instance = null;
  private Properties props = new Properties();
 
  private MailProperties() throws Exception {
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/property/mail.properties");
    if (is != null) props.load(is);
  }
 
    public static MailProperties getInstance() throws Exception {
    if (_instance == null) _instance = new MailProperties();
    return _instance;
  }
 
  public String getProperty(String name) throws Exception {
    return props.getProperty(name);
  }
 
  public int getIntProperty(String name) throws Exception {
    return Integer.parseInt(getProperty(name));
  }
 
}

This class is hooked into a jar file and loads all properties found in the package com/property/. Once we call the class’ getInstance() method, a static object will be called that holds all properties found in the mail.properties file. This way, whenever we call it to retrieve a property, the object will only be instantiated once and called as many times.

To retrieve a property, you can call it like this:

1
System.out.println(MailProperties.getInstance().get("my_property"));

Found this post useful? Buy me a cup of coffee or subscribe to my RSS feeds and Google Friend Connect

Related Posts with Thumbnails

tags: ,

One Response to “Creating A Singleton Using Java”

  1. 1
    my daily thoughts Says:

    hmmm very confusing codes..
    Blogger”s Recollections
    Array Of Hopes

Leave a Reply

Spam protection by WP Captcha-Free