Java: getInstance vs Static

后端 未结 6 884
清歌不尽
清歌不尽 2021-01-30 11:17

What is the purpose of getInstance() in Java?

During my research I keep reading that getInstance() helps achieve a Singleton design pattern (w

6条回答
  •  野性不改
    2021-01-30 11:48

    The exact method of implementing a singleton, for example using a factory method called getInstance(), isn't that relevant to the question, which is "static methods vs singleton with instance methods".

    Classes are themselves effectively singletons, so from that aspect they are similar.

    The main difference is that static methods are not part of class hierarchy - they are not inherited, which means the static method option locks you forever to using that exact class and it can't be referred to in any other way, such being an implementation of some interface or a super class.

    Instances however don't have this problem, so you can code for example:

    class MySingleton implements SomeInterface {
        ...
    }
    
    SomeInterface instance = MySingleton.getInstance();
    

提交回复
热议问题