create a singleton class in java using public constructor - java

Do I have to use private constructor to make a class singleton? Is there any other way than using private constructor?
Can't I make a class singleton using public constructor?

If your class has a public constructor, then anybody can create an instance of it at any time. So it's not a singleton any more. For a singleton, there can exist only one instance.

The reason it has to be a private constructor is because you want to prevent people from using it freely to create more than one instance.
A public constructor is possible only if you are able to detect an instance already exist and forbid a another instance being created.
Is there no way other than using private constructor ? Can't we make a class singleton using public constructor ?
Yes, it is actually possible, for example:
class Singleton
{
private static Singleton instance = null;
public Singleton() throws Exception //Singleton with public constructor
{
if(instance != null)
throw new Exception("Instance already exist");
//Else, do whatever..such as creating an instance
}
}

If you really must use public constructor, then you should check whether instance is null and throw an exception.
if(instance != null)

One way to create Singleton object using public constructor with throw exception from constructor if object is already exist.
For Example:
public class Singleton {
private static Singleton singleton;
private String hello;
public Singleton() throws Exception {
if (singleton != null) {
throw new Exception("Object already exist");
}
}
public static Singleton getInstance() throws Exception {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public static void main(String[] args) {
try {
Singleton single1 = Singleton.getInstance();
single1.setHello("Hello");
System.out.println(single1.getHello());
Singleton single2 = Singleton.getInstance();
System.out.println(single2.getHello());
Singleton single3 = new Singleton();
System.out.println(single3.getHello());
} catch (Exception ex) {
}
}
}

Generally, Singleton pattern is used when you should have exactly 1 object of a class (e.g. Factories are very often implemented as Singletons).
public modifier allows anyone to access your method (as well as your constructor). In that case, anyone can create an instance of your class, thus it won't be a singleton anymore.
By setting private modifier to your constructor, you are sure, it cannot be used outside of the class - no one will create any more objects of that class.
public class SingletonExample {
private static final SingletonExample instance;
// Initialize instance object in static block - done while loading the class by class loader
static {
instance = new SingletonExample();
}
private SingletonExample(){}
public static SingletonExample getInstance(){
return instance;
}
// Method used to create java.test.DateFormat using Oracle SQL Date pattern
public DateFormat createDateFormat(String mask){
if("DD-MM-YYYY HH24:MI:SS".equals(mask)){
return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
} else if("DD-MM-YYYY".equals(mask)){
return new SimpleDateFormat("dd-MM-yyyy");
} else {
throw new UnsupportedOperationException("Unsupported mask - " + mask);
}
}
}
And usage example
public class SingletonExampleTest{
public static void main(String... args){
java.util.Date date = Calendar.getInstance().getTime();
SingletonExample singleton = SingletonExample.getInstance();
String mask = "DD-MM-YYYY";
DateFormat df = singleton.createDateFormat(mask);
System.out.println(df.format(date));
}
}

The private constructor is a reason, why your class is Singleton.
This Example shows pretty well, how you can use your Singleton class by using getInstance()

Related

Implement singleton with static access modifier in Java

Example class with singleton design pattern.
class Singleton {
private static Singleton instance;
private int x;
private Singleton() {
x = 5;
}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
System.out.println("Hello");
}
}
I'm just wondering can I create this class with same variables and methods declared as static. Is it same as the singleton?
Singleton should be considered only if all three of the following criteria are satisfied:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
Yes, It is the same.
If you really need to implement a singelton pattern I would recommend using an enum:
public enum MySingelton{
INSTANCE;
private final String[] variable = new String[]{"test", "test2};
public void randomFunction(){
}
}
Call it with:
MySingelton.INSTANCE.randomFunction();
With an enum implementation it's guaranteed that only one instance is created and that it's available all the time. Also it's possible to serialize and deserialize the singelton without creating multiple copies of it.
More information can be found here:
What is an efficient way to implement a singleton pattern in Java?
http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883?pgno=3
Since the purpose of the singleton pattern is to ensure that a single instance of a class exists, yes, you could use static members to achieve the same effect.
So instead of
public class Singleton {
private static Singleton theInstance = new Singleton();
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
return theInstance;
}
}
you could do
public class FakeSingleton {
private static int aVar = 10;
public static void aMethod() {
System.out.println(aVar);
}
}
and have exactly the same functionality (instead of Singleton.getInstance().aMethod() you would write FakeSingleton.aMethod()).
Using the singleton pattern can be advantageous if you want lazy initialization, so that the singleton is only initialized when it is first needed, as follows:
public class Singleton {
private static Singleton theInstance = null;
private int aVar = 10;
public void aMethod() {
System.out.println(aVar);
}
public static Singleton getInstance() {
if (theInstance == null) {
theInstance = new Singleton();
}
return theInstance;
}
}
(Note that the above is not thread-safe, in multithreaded code you will need to add synchronization.)

Java Singleton has different toString() value

I have a classic singleton implemented in java
public class ClassicSingleton {
private static ClassicSingleton instance = null;
private ClassicSingleton() {} ;
public static ClassicSingleton getInstance() {
if (instance == null)
return new ClassicSingleton();
return instance;
}
}
I have the following driver
public class SingletonDriver {
public static void main(String[] args) {
System.out.println(ClassicSingleton.getInstance().toString());
System.out.println(ClassicSingleton.getInstance().toString());
}
}
The output is something like
ClassicSingleton#75e4f66a
ClassicSingleton#aede59e
I thought the output would be pointing to the same object. Shouldn't the values be the same?
Your implementation of getInstance() is wrong. You never initialize instance, and thus return a new instance on each invocation. If instance is null, you should save it to your data member, and only then return it:
public static ClassicSingleton getInstance() {
if (instance == null)
instance = new ClassicSingleton();
return instance;
}
You forgot to assign new ClassicSingleton() to instance, so you actually have a factory instead of a singleton; you'll create a new instance on every call. (Note also, of course, that this isn't thread-safe.)

Singleton instantiated with this

I have an assignment for school where I have to spot patterns in a certain given project. All is well (well, relatively..) but it seems that most patterns I find are some sort of variation. The singleton I had to find is no different.
The code is given below. The strange thing about this is that this class does not seem to instantiate with the following constructor, as one would expect:
public Singleton() {
if (singleton == null) {
singleton = new Singleton();
}
}
However, it is instatiated with this (as you can see in the original code below)? In my understanding this creates some sort of static singleton? I debugged and saw indeed that the first time the constructor is called by
Singleton x = new Singleton();
x.Print();
, it is indeed null. And this is a Singleton instance. However, shouldn't there be
private static Singleton singleton = new Singleton();
on top of the class instead of singelton = this;?
public class Singleton {
private static Singleton singleton;
public static Singleton getDefault() {
return singleton;
}
/**
* The constructor.
*/
public Singleton() {
if (singleton == null) {
singleton = this;
}
}
public void Print()
{
System.out.println("I'm a singleton!");
}
}
I'm pretty sure it is indeed a singleton, it's just of the type I have never seen and I don't get reasoning behind it, that's what I'm basicly asking.
There is generally two approaches to creating a Singleton class, both are based on keeping the constructor private.
The first approach:
public class Singleton
{
public static final Singleton INSTANCE = new Singleton();
private Singleton{...}
}
You create an instance like this: Singleton single = Singleton.INSTANCE;
The second approach:
public class Singleton
{
private static final Singleton INSTANCE = new Singleton();
private Singleton(){...}
public static Singleton getInstance(){ return INSTANCE; }
}
In this case, you create an instance like this: Singleton single = Singleton.getInstance();
The getInstance() method is then regarded as a public factory method.
As you can see, in both cases the new keyword is definitely used to create a single instance of the class, but because of the pattern used, there can only be one instance and no more. You don't need to use the "this" keyword.
Hope this helps.
Your code has not followed the Singleton pattern. I have shown below a class following the Singleton pattern. this refers to the current object instance. When you initialize the singleton reference with this inside constructor, it calls the default (no-args) constructor and assigns it back to the this reference and then it is assigned to singleton class member variable
public class Singleton {
private static Singleton singleton;
public static Singleton getDefault() {
if (singleton == null)
singleton = new Singleton();
return singleton;
}
/**
* The constructor.
*/
private Singleton() {
System.out.println(singleton);
if (singleton == null) {
/*this will call a default constructor
*and instantiate Singleton object
*/
singleton = this;
}
}
public void Print() {
System.out.println("I'm a singleton!");
}
public static void main(String[] args) {
Singleton singleton = Singleton.getDefault();
System.out.println(singleton.Print());
}
}
Hope you can understand!
I think you are confusing the meaning or this. this is not instantiating the class, this references the newly created instance. Then whenever someone calls your constructor a new instance is created (and returned) no matter you store in private static Singleton singleton; or not.
As well said #dic19 you must make your constructor private for preventing more than one instance to exist.
If the point is not to modify the code as you said, then the point is to report that this class is NOT a singleton.
You can check debugging:
Singleton x = new Singleton();
Singleton x1 = new Singleton();
Singleton x2 = new Singleton();
You will see all three are different instances, being Singleton.getDefault() simply the first you created.
If we use singletone we do not need to create instance for use. Because when we are creating singletone then we are creating new instance if not created.
Take a look of below code :
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public void testSingleTone(){
System.out.println("test");
}
public static void main(String[] args){
Singleton.getSingleton().testSingleTone();
}
}

Creating java singleton with static inner class

I want to use the following pattern to create a singleton in java
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
But what happens when the private constructor I want to call is
private Singleton(Object stuff) {... }
How do I pass stuff to INSTANCE = new Singleton()? As in INSTANCE = new Singleton(stuff);
Rewriting the above snippet:
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton(Object stuff) { ... }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(Object stuff) {
return SingletonHolder.INSTANCE;//where is my stuff passed in?
}
}
EDIT:
for those of you claiming this pattern is not thread safe, read here: http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh.
The object I am passing in is the android application context.
If you really want a singleton, there should be only one instance of it (duh!). If you add a parameter to getInstance you probably expect the returned instance to be different (otherwise there is no need for a parameter) which defeats the purpose.
If your goal is to add some configuration when the only instance is created, the simplest way would be to have your singleton query for the configuration information when it is instantiated:
public static final Singleton INSTANCE = new Singleton(getConfiguration());
where getConfiguration returns what is needed (whether by reading a file or forwarding some other variable for example).
Usual disclaimer: Singletons are evil.
Additional resource: Google guide to writing testable code (in case you were not convinced the first time).
You might want to read
a singleton with parameters is not a singleton
The first answer argues why a >>singleton with parameters<< is not a singleton, and doesn't come near a singleton.
public class Singleton {
private static Singleton singleton;
// Private constructor prevents instantiation from other classes
private Singleton() { }
public void addStuff(Object stuff){}
public static Singleton getInstance() {
if(singleton == null) singleton = new Singleton()
return singleton;
}
}
and use it as:
Singleton s = Singleton.getInstance();
s.addStuff(stuff);
or an alternative
public class Singleton {
private static Singleton singleton;
// Private constructor prevents instantiation from other classes
private Singleton() { }
public static void redefine(Object stuff){
singleton = new Singleton(stuff) // choose constructor based on parameters
}
public static Singleton getInstance() {
return singleton;
}
}
Why not get rid of SingletonHolder use factory pattern. You will have to decide what to do, when try to call getInstance twice, but with different 'stuff'.
public class Singleton {
private static Singleton singleton
private final Object stuff;
private Singleton(Object stuff) {
this.stuff = stuff;
}
public static synchronized Singleton getInstance(Object stuff) {
if (singleton == null) {
singleton = new Singleton(stuff);
return singleton;
}
return singleton; // or throw error because trying to re-init
}
}

Singleton class Identification

Can anyone please tell me whether this is a singleton class or not?
public class Final_output{
Cafe_factory obj=null;
private Final_output()
{
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public static void main(String args[])
{
new Final_output();
}
}
Cafe_factory is another class in the same package.
This is not a Singleton.
Singleton for Example is:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Not, it's not. Because you can't create instances of this class outside of it (at least one instance should exist). For the other hand - you can create as many instances inside main as you wish (so it's not singleton either).
Here is an example of Singleton:
public class MySingleton{
private MySingleton(){}
private static InstanceHolder{
private static final MySingleton instance = new MySingleton();
}
public static MySingleton getInstance(){
return InstanceHolder.instance;
}
}
Its not.
A singleton has as objective to limit to 1 the number of instances of the same class that can be created, and provide static methods to retrieve this instance.
This is typically done via a private constructor and static methods to retrieve this unique instance. Here neither Final_output nor Cafe_factory respect this contract so none of them use the singleton pattern.
Since you could create n amount of new Cafe_Factory objects in your code also outside the Final_output class, no it is not a singleton. A singleton is never created with the new keyword. Instead, you fetch an instance of it via a static method.
this :
public class Final_output{
private static Cafe_factory obj = null;
private Final_output()
{
obj = getCafeInstance();
}
public static getCafeInstance(){
if(null == obj){
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}else{
return obj;
}
}
}
NO This is not a singleTon
public class Final_output{
private static Final_output ourInstance = new Final_output();
Cafe_factory obj=null;
private Final_output() {
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public Final_output getINstance(){
return ourInstance;
}
}

Categories