Thursday, October 30, 2014

Singleton Pattern

package com.exmpl.singleton;

public class PatternClass {
       // 1. create an object of PatternClass.
       private static PatternClass instance = new PatternClass();

       // 2. Create a private constructor, so that this class can not be
       // instantiated.
       private PatternClass() {
              // No argument constructor.
       }

       // 3. Create a getter method of "instance" property, which return instance
       // of "PatternClass".
       public static PatternClass getInstance() {
              return instance;
       }

       // Normal method.
       public void displayMessage() {
              System.out.println("I am displayMessage() under PatternClass.");
       }
}
package com.exmpl.singleton;

public class ClientClass {

       public static void main(String[] args) {
              /*
               * We can not create an instance of "PatternClass" as below, because of
               * private constructor. The following line will shown an compilation
               * error.
               */
              // PatternClass patternClass = new PatternClass();

              /*
               * Get the instance of "PatternClass", by calling "getInstance()"
               * method.
               */
              PatternClass patternClass = PatternClass.getInstance();
              // Now calling "displayMessage()" method.
              patternClass.displayMessage();
       }
}

Output รจ I am displayMessage() under PatternClass.

No comments:

Post a Comment