Which is a better singleton implementation?

孤街浪徒 提交于 2019-12-24 03:36:27

问题


I was looking at these two implementations of the Singleton Pattern:

 Class Customer {

int x;
static int count = 0;

private Customer()
{
    x = 1;
}

public static Customer GetCustomer()
{
    if(count==0)
    {
        count++;
        return new Customer();
    }
    else
    {
        return null;
    }
}
}

Implementation 1 in which the constructor is not called if the class is already instantiated once. OR

 Class Customer{

int x;
static int count = 0;
public Customer()
{
    if(count == 0)
    {
        x = 1;
        count++;
    }
    else
    {
        return;
    }
}

Implementation 2 in which the constructor is called irrespective of weather the class is already instantiated once or not. I watched a video lecture online that says Implementation 2 is not preferred as it allocates memory for the constructor although the object is not instantiated for the second time. I am aware Java has automatic Garbage Collection, but just wanted to know if what I watched in the video lecture is relevant.


回答1:


There are some that would say that no implementation of a singleton is the correct one, but I'm not quite in that camp.

People often tend to use them badly (as a God object, for example) but they still have their place (in my opinion, which has little to do with this answer).

For the purposes of this answer, I'm going to assume you've made the right decision in needing a singleton, but I do urge you to read up on its potential problems - there may well be a better way to achieve your ends.


Having said that, I'm not sure if your code samples are correct anyway. A singleton is supposed to return one and only one instance, creating one if necessary, giving you the previously created one if not.

I fail to see how your first code sample honors that contract. It'll give you a new one the first time it's called, then it will give you nothing after that.

And your second code sample doesn't seem to prevent multiple objects at all.

So I'd be thinking very carefully about whether you want to continue watching that video, if this is the quality of the education they deliver.


In any case, I prefer the one that only constructs once, since you're only supposed to have one object of that class. In other words, a static getMe() call that is properly synchronised to prevent race conditions allowing creation of more than one Me object, and that creates a new object the first time, returning that same object on subsequent calls.

In pseudo-code, that would be something like:

class Me {
    private Me() {};

    private static Me *loner = NULL;

    public static synchronised Me *getMe() {
        if loner == NULL
            loner = new Me();
        return loner;
    }
}



回答2:


Writing a correct singleton is not that easy. You need to take care of race conditions and to defend against reflection attacks. For example a private constructor might be invoked via reflection to create one more instance of an object. The easiest and safest singleton implementation in java is done with an enum:

enum Singleton {
    INSTANCE;
}

That's because enum constants are spedified by JLS to be singletons (section 8.9 of JLS):

An enum type has no instances other than those defined by its enum constants.



来源:https://stackoverflow.com/questions/12255810/which-is-a-better-singleton-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!