简体   繁体   中英

Java static instance VS get-method

I've been thinking about the difference between these code snippets. I understand that you can not set instance field if you are using getInstance (Second option below), but is there other differences?

public class MainClass {
    public static MainClass instance;

    public static void main(String[] args) {
        instance = new MainClass();
    }

    public void HelloWorld() {
        System.out.println("This is a test!");
    }
}

VS

public class MainClass {
    private static MainClass instance;

    public static void main(String[] args) {
        instance = new MainClass();
    }

    public MainClass getInstance() {
        return instance;
    }

    public void HelloWorld() {
        System.out.println("This is a test!");
    }
}

What is the difference between using "MainClass.instance.HelloWorld();"(First) or "MainClass.getInstance().HelloWorld();" (Second)

TLDR: Which one, and why? What is the difference?

Thanks! :)

In the first example, you have declared instance as public making it vulnerable to accidental changes and therefore it is not recommended.

In the second example, you have declared instance as private making it invisible outside the class and thus ensuring that if required, it can be changed only through a public mutator/setter where you can put the desired logic how you want it to be changed.

Scalability

The difference is somewhere down the line if your program has many calls to the instance, and you want to change where the instance comes from or perform an additional action while retrieving the instance, you can modify the getInstance() method, instead of adding code in every location where you used instance .

Public

Current code is vulnerable by outsider who can change your instance with new one or even their own by subclassing. If you do not have need to change instance after first init then make it final and then public is good.

private

Saves you from above problem. Gives you more control to change instance if needed.

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