Practical Singleton & Dependency Injection question

前端 未结 5 1030
名媛妹妹
名媛妹妹 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:34

    So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?

    Yes, this is all you need to do. Whether a dependency is a singleton / per request / per thread or a factory method is the responsibility of your container and configuration. In the .net world we would ideally have the dependency on an IPermissionsManager interface to further reduce coupling, I assume this is best practice in Java too.

提交回复
热议问题