Singleton Design Pattern in JAVA

Singleton Design Pattern in Java aims to restrict access to a class by creating a single static instance/object of the class and providing global access to it through a method. However, no new instances can be created as constructor is marked private.

For instance:

public class SingletonDesign {

// Single object created.

private static SingletonDesign singletonDesignObject = new SingletonDesign():

// Private constructor which can’t be accessed to create instances.

private SingletonDesign() {}

// Global method that would provide access to the ONLY instance of this class.

public static SingletonDesign newInstance() {

return singletonDesignObject;

}

public int getValue() {

return 5;

}

}

// Test Class

public class TestSingleton {

@Test

public void testSingletonClass() {

// Accessing the only object available

SingletonDesign singletonDesign = SingletonDesign.newInstance();

int value = singletonDesign.getValue();

System.out.println(value);

}

}

Advantages of Singleton Pattern:

  1. There would exist one object of this class at any point of time.

Disadvantages of Singleton Pattern:

  1. They cause code to be tightly coupled against loose coupling which should be done. This is because every class which has to access this class will have to depend on the only object available of this class and can’t be independent.

 

 

 

 

 

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