Practical Singleton & Dependency Injection question

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

    If you are using a dependency-injection framework, then the common way to handle this is to either pass in a PermissionsManager object in the constructor or to have a property of type PermissionsManager that the framework sets for you.

    If this is not feasible, then having users get an instance of this class via factory is a good choice. In this case, the factory passes the PermissionManager in to the constructor when it creates the class. In your application start-up, you would create the single PermissionManager first, then create your factory, passing in the PermissionManager.

    You are correct that it is normally unwieldy for the clients of a class to know where to find the correct PermissionManager instance and pass it in (or even to care about the fact that your class uses a PermissionManager).

    One compromise solution I've seen is to give your class a property of type PermissionManager. If the property has been set (say, in a unit test), you use that instance, otherwise you use the singleton. Something like:

    PermissionManager mManager = null;
    public PermissionManager Permissions
    {
      if (mManager == null)
      {
        return mManager;
      }
      return PermissionManager.getInstance();
    }
    

    Of course, strictly speaking, your PermissionManager should implement some kind of IPermissionManager interface, and that's what your other class should reference so a dummy implementation can be substituted more easily during testing.

提交回复
热议问题