简体   繁体   中英

Design Singleton Pattern - Constructor

I am unable to create an object using singleton design pattern, here is what I did:

class Test {
    public static Test objTest = null;
    public static int count = 0;

    public static Test CreateObject() {
        if (objTest != null)
            objTest = new Test(); 
        return objTest;
    }

    private Test() {
        Test.count++;
    }
}

Have I created zeroton pattern ?

Check your if condition inside createObject method once. it should be if(objTest == null) .

Besides the fact, that your count would always be either '0' or '1' (ignoring potential multi-threading issues) - why do you have that parameter?

You are checking for objTest != null instead of objTest == null .

That's why you are always returning null and never create a new instance.

The objTest variable should also be private, you'll not want to reference to a null instance. Access to the instance should only be possible through your CreateObject() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM