Monday, September 7, 2020

SINGLETON

package com.exam.desingpattern;


public class Singleton implements Cloneable  {

static Singleton singleton;

public static Singleton getInstance()

{

if (singleton == null)

{

return new Singleton();

}

else

{

return singleton;

}

}

   @Override

    protected Object clone() throws CloneNotSupportedException {


        // TODO Auto-generated method stub

        /*

         * Here forcibly throws the exception for preventing to be cloned

         */

        throw new CloneNotSupportedException();

        // return super.clone();

    }

   

   public static void main(String[] args) {

        // TODO Auto-generated method stub

   Singleton test1 = Singleton.getInstance();


        try {

        Singleton test2 = (Singleton) test1.clone();

        } catch (CloneNotSupportedException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }


}


No comments: