SINGLETON PATTERN EXAMPLE PROGRAM IN JAVA

 /**  
 Singleton Pattern: One instance of a class or one value accessible globally in an application.   
 There are some instances in the application where we have to use just one instance.   
 In this Example:   
 We use Static variable to control the instance variable.   
 */  
 class Connection {  
      public static boolean haveOne = false;  
      public Connection() throws Exception{ // constructor   
           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());  
     }  
   }  
 }  
 /*  
 We can reach Singleton Pattern with 2 approaches  
 1.Static Methods   
 2.Static Classes   
 This Example is Static Method in the next example we do it using Static Class.   
 */  

Post a Comment

0 Comments