How can a singleton class use an interface?

后端 未结 5 1889
盖世英雄少女心
盖世英雄少女心 2021-02-04 11:09

I read at many places that singletons can use interfaces. Some how I am unable to comprehend this.

5条回答
  •  日久生厌
    2021-02-04 11:33

    I think I understood your problem. You want to define factory method in interface (static method to getInstance()). But since factory method can't be defined in interface, that logic will not work.

    One option is to have a factory class which holds that static method. So there will be three classes first class to hold static method second is the interface third is the concrete class

    But we can not make the concrete constructor private.

    But if your infrastructure has two packages one for public and the other for private

    define interface in public, make concrete class package level (with out any access modifier) and Factory class and static method be public.

    I hope this could help you.

提交回复
热议问题