Design pattern to use instead of multiple inheritance

后端 未结 8 2544
离开以前
离开以前 2020-12-09 03:16

Coming from a C++ background, Im used to multiple inheritance. I like the feeling of a shotgun squarely aimed at my foot. Nowadays, I work more in C# and Java, where you can

8条回答
  •  醉话见心
    2020-12-09 03:31

    • In .Net, you can have extension methods apply to interfaces. It's really neat when it's possible, and applicable for you because it's a rare way to apply a common implementation to an interface. Certainly consider it, but it might not work for you since you say that DoMagic works with a lot of Private members. Can you package these private variables internal possibly? This way the extension method could access them.
    • Have the common functionality in another class. If there's a logical place to put this common functionality, pass your objects to this other class method (perhaps this is UI functionality, and you already have a UI helper . . .). Again, can you expose the private data with an internal/public property? (Security/encapsulation is a concern in all this of course. I don't know if your classes are for internal use only or will be exposed publicly.)
    • Otherwise, pass a separate functionality class (or specific function pointer) into the interface-defined method. You would have to have a little bit of duplicated code to pass your private variables to this external function reference, but at least it wouldn't be much, and your implementation would be in one place.
    • We might be making this too complicated. It won't make you feel all object-oriented when you go to sleep tonight, but could you have a static routine in your library somewhere that all IMagician implementers call?
    • In the end, Adapter might indeed be what you're looking for. Less likely but still worth consideration is the Decorator pattern.

    If nothing seems particularly good, pick what feel best, use it a couple times, and rearrange tomorrow. :)

提交回复
热议问题