go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  Singleton Pattern
 
Subject: Singleton Pattern
Author: Alex_Raj
Posted on: 12/05/2013 07:20:23 PM

As its name suggests, singleton is a class that is instantiated only once across your application environment. This is typically accomplished by creating a static field in the class representing the class.

Two key points of a single design pattern:

  • only one instance allowed for a class

  • global point of access to that single instance


  • Here is an example (not right though):
    public class Singleton 
    {
        /* static field to ensure only one copy */
        private static Singleton instance;
    
        /* private constructor to prevent it from being instantiated from outside */
        private Singleton() {
        }
    
        /* public static method to ensure global point of access */
        public static Singleton getInstance() 
        {
            if(instance==null){
                instance = new Singleton();
            }
            return instance;
        }
    
        public void sayHello() {
            System.out.println("Hello");
        }
    }
    



    Replies:


    References:

     


     
    Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
     
    Get your own forum today. It's easy and free.