dimanche 23 juillet 2017

Is this correct demonstration of faulty singleton pattern implementation?

I read about the Singleton Pattern from here http://ift.tt/1juRdSp and it has described some common implementation mistakes. I just want to check if these programs I have written do demonstrate their incorrectness.

In the first program, I have created an inherited class and called the protected constructor of the base class. This allows me to create 2 instances of Singleton.

import java.util.*;
import java.lang.*;
import java.io.*;

class Singleton {
    public static Singleton Instance() {
        if (_instance == null) {
            _instance = new Singleton();
            return _instance;
        }
        return _instance;
    }
    protected Singleton() {}
    private static Singleton _instance = null;
}

class SingletonBasher extends Singleton {
    public SingletonBasher() {

    }
}

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Singleton x = new Singleton();
        Singleton y = SingletonBasher.Instance();
        if(x != y)
            System.out.println("fail!");
    }
}

In the second program I have simply created two objects using new operator and this works because the constructor is protected. Had it been private, I would have been forced to use the Instance method which will only allow me to create 1 instance.

import java.util.*;
import java.lang.*;
import java.io.*;

class Singleton {
    public static Singleton Instance() {
        if (_instance == null) {
            _instance = new Singleton();
            return _instance;
        }
        return _instance;
    }
    private Singleton() {}
    private static Singleton _instance = null;
}


class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Singleton x = Singleton.Instance();
        Singleton y = Singleton.Instance();
        if(x != y)
            System.out.println("fail!");
    }
}

Aucun commentaire:

Enregistrer un commentaire