Skip to main content

Posts

Showing posts from October, 2009

SingleTon DesignPattern

Singleton pattern comes into creational design pattern category, the main objective of the creational pattern is to instantiate an object and with Singleton Pattern we will allow only one instance of the class to be created. Here in this article we will understand how we can create an Singleton class in Java. Singleton Class Code: package designpattern.creational.singleton ; public class MySingleTon { private MySingleTon ( ) { } private static MySingleTon instance = null ; public static synchronized MySingleTon getInstance ( ) { if ( instance == null ) { System . out . println ( "Creating New Instance" ) ; instance = new MySingleTon ( ) ; } else { System . out . println ( "Returning Existing Instance" ) ; } return instance ; } public Object clone ( ) throws CloneNotSupportedException { throw new CloneNotSupportedException ( ) ; } } Code Explanation: W