Singleton Pattern

The Singleton Pattern basically restricts the instantiation of a class to one object.

An very simple example of this is as follows:

    public class Singleton {

        private static Singleton singleton = new Singleton();
        private static double randomNumber = (Math.random() * 100000);

        /* A private Constructor prevents any other
        * class from instantiating.
        */
        private Singleton(){ }

        /* Static ‘instance’ method */
        public static Singleton getInstance() {
            return singleton;
        }

        /* Other methods protected by singleton-ness */
        protected static void demoMethod() {
            System.out.println(“demoMethod for singleton (” + randomNumber + “)”);
        }
    }

    public class SingletonDemo {

        public static void main(String[] args) {
            Singleton tmp = Singleton.getInstance( );
            tmp.demoMethod( );

            Singleton tmp2 = Singleton.getInstance( );
            tmp2.demoMethod( );
        }
    }

The reason we include a random number is to prove that we get the same instance of Singleton whenever we call getInstance().

 

TRP

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s