java4all@1986 java. Powered by Blogger.

What is meant by Singleton Pattern?

>> Friday, May 27, 2011

SINGLETON:
                       One instance of a class or one value accessible globally in an application. 


Where to use & benefits



For example, to use a static variable to control the instance;
class Connection {
    public static boolean haveOne = false;
    public Connection() throws Exception{
        if (!haveOne) {
           doSomething();
           haveOne = true;
        }else {
          throw new Exception("You cannot have a second instance");
        }
    }
    public static Connection getConnection() throws Exception{
        return new Connection();
    }
    void doSomething() {}
    //...
    public static void main(String [] args) {
        try {
            Connection con = new Connection(); //ok
        }catch(Exception e) {
            System.out.println("first: " +e.getMessage());
        }
        try {
            Connection con2 = Connection.getConnection(); //failed.
        }catch(Exception e) {
            System.out.println("second: " +e.getMessage());
        }
    }
}

0 comments:

Post a Comment

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP