Practical Singleton & Dependency Injection question

前端 未结 5 1031
名媛妹妹
名媛妹妹 2021-02-07 10:11

Say I have a class called PermissionManager which should only exist once for my system and basically fulfills the function of managing various permissions for various actions in

5条回答
  •  情书的邮戳
    2021-02-07 10:26

    If you are subscribing to the dependency injection way of doing things, whatever classes need your PermissionManager should have it injected as an object instance. The mechanism that controls its instantiation (to enforce the singleton nature) works at a higher level. If you use a dependency injection framework like Guice, it can do the enforcement work. If you are doing your object wiring by hand, dependency injection favors grouping code that does instantiation (new operator work) away from your business logic.

    Either way, though, the classic "capital-S" Singleton is generally seen as an anti-pattern in the context of dependency injection.

    These posts have been insightful for me in the past:

    • Using Dependency Injection to Avoid Singletons
    • How to Think About the "new" Operator with Respect to Unit Testing

提交回复
热议问题