I am trying to create an object that can call one of 3 methods in response to user input. Let's call them, DoShape
, DoColor
, and DoPowerTool
. These methods exist as part of a base class and interfaces respectively:
Public Class PowerTool
{
...
public virtual void DoPowerTool()
{
...
}
}
Public Interface Shape
{
void DoShape(PowerTool p);
}
Public Interface Color
{
void DoColor(PowerTool p);
}
As DoShape
and DoColor
require a PowerTool, the intuitive thing would be to somehow bake those methods into the PowerTool instance itself.
Unfortunately, I can't have the PowerTool class implement Shape and Color directly, since I won't know until runtime if it's a Red Square Jackahmmer or a Green Ovoid one.
I've dabbled with C#'s delegates, and have a feeling that they might be useful in this case, but I'm not familiar enough to know how to implement them in this precise scenario, and I'm unsure if they're the right choice to give me the modular behavior I'm looking for. (I may be spoiled by Javascript in this regard, where you can simply overwrite functions on objects).
Any thoughts or suggestions on how to continue? I feel like there's probably a very simple solution that I'm overlooking in all this.
I believe what you are referring to is the concept of a Mixin.
This is where one or many implementations for an interface are defined, and then the implementations are reused for their concrete types.
This is unfortunately not really possible in .NET because the framework was desgined without that ability to use multiple inheritance. Though, you may be able to replicate the behavior you're seeking using extension methods or, through dependency injection and the strategy pattern.
If you have any further questions about the patterns, or require more applicable examples, just let me know what you're attempting to accomplish in more detail and I will do my best to help.
If I understand what you are describing, the following strategy pattern may be of benefit:
internal interface IPowerToolStrategy
{
void Execute(PowerTool powerTool);
}
public class RedSquareJackhammer : IShape
{
private readonly IPowerToolStrategy _strategy;
internal RedSquareJackhammer(IPowerToolStrategy strategy)
{
_strategy = strategy;
}
public void DoShape(PowerTool powerTool)
{
_strategy.Execute(powerTool);
}
}