lundi 15 août 2022

Allow class to modify singleton only if it has implemented interface

I have a singleton that's acting as a core setup and manager for a large application. I want to restrict write access to callers outside the singleton but still allow it only if they've implemented a specific interface I define (e.g., ICoreModifier)

The desired outcome is below:

public class Core
{
    // singleton code omitted

    int Property { get; set; }
}
public class A : ICoreModifier
{
    // implemented ICoreModifier so things are okay
    Core.GetInstance().Property = 1;
}
public class B
{
    // No ICoreModifier implementation so this results in compile or runtime error
    Core.GetInstance().Property = 1;
}

However, there's two issues I'm running into with this.

  1. I'm having trouble coming up with what would actually go on the interface. This tells me I must be following the wrong design structure. I'm open to alternative approaches. I've been thinking about some sort of Lock and Unlock kind of method implementation requirement, but delegating write access to the person asking to write sounds like a bad idea and probably wouldn't even work.

  2. Ideally, I'd like for this to be a compile time error rather than runtime. If that's not possible that's okay, but I'm still not quite sure how I go about doing a runtime check. My current thinking is to use reflection, but that seems messy and not very robust.

I've considered inheritance as well, but my understanding is that inheritance is with regard to is-a relationships. The classes getting write access are not cores themselves. This is why the can-do relationship interfaces provide seem most appropriate to me here.

How can I accomplish this?

Aucun commentaire:

Enregistrer un commentaire