How can we make a class Singleton?

View previous topic View next topic Go down

How can we make a class Singleton?

Post  Admin on Sat Aug 27, 2011 11:56 am

A) If the class is Serializable


class Singleton implements Serializable
{
private static Singleton instance;

private Singleton() { }

public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}

/**
If the singleton implements Serializable, then this
* method must be supplied.
*/
protected Object readResolve() {
return instance;
}

/**
This method avoids the object fro being cloned
*/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}
}

B) If the class is NOT Serializable


class Singleton
{
private static Singleton instance;
private Singleton() { }

public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}

/**
This method avoids the object from being cloned
**/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}

}

Admin
Admin

Posts : 131
Join date : 2011-08-16

View user profile http://codefornongeek.forumotion.com

Back to top Go down

Re: How can we make a class Singleton?

Post  Admin on Sat Aug 27, 2011 2:26 pm

class Singleton{
private static Singleton instance;
private Singleton();
public static synchronized Singleton getInstance(){
if(instance==null)
instance=new Singleton();
return instance;
}
}

Admin
Admin

Posts : 131
Join date : 2011-08-16

View user profile http://codefornongeek.forumotion.com

Back to top Go down

Re: How can we make a class Singleton?

Post  Admin on Sat Aug 27, 2011 2:31 pm

Singleton to handle Multi-threading:

class Singleton{
private static Singleton instance;

private Singleton(){}

public static Singleton getInstance(){
if(instance==null){
synchronized (Singleton.class){
if(instance==null){
instance=new Singleton();
}

}
}
return instance;
}
}

Admin
Admin

Posts : 131
Join date : 2011-08-16

View user profile http://codefornongeek.forumotion.com

Back to top Go down

Re: How can we make a class Singleton?

Post  Admin on Sat Aug 27, 2011 2:42 pm

Singleton to handle Multi-threading:

1 way: make the method synochronized (but will influence performance)

2 way: double check locking
class Singleton{
private static Singleton instance;

private Singleton(){}

public static Singleton getInstance(){
if(instance==null){
synchronized (Singleton.class){
if(instance==null){
instance=new Singleton();
}

}
}
return instance;
}
}

Admin
Admin

Posts : 131
Join date : 2011-08-16

View user profile http://codefornongeek.forumotion.com

Back to top Go down

Re: How can we make a class Singleton?

Post  Sponsored content


Sponsored content


Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum