vendredi 2 avril 2021

How can I provide new behavior to an interface in C#?

I would like to modify the behavior of a class instance that implements a particular interface. The modification is performed by a modifier object. In the end, the original class instance should still retain all of its other behavior. Here's the setup:

The interfaces and implementing class look like this:

interface IFuncA
{
  double DoSomethingA();
}
interface IFuncB
{
  int DoSomethingB(string str);
}

class ImplementsAB : IFuncA, IFuncB
{
  void DoSomethingA() => 3.14;
  int DoSomethingB(string str) => str.Length;
}

There is some modifier class that works according to the following psuedocode. This is the part that I can't exactly figure out.

// Unknown how to make this work.
class ModifiesFuncB
{
  int Multiplier;
  int ModifiedDoSomethingB(string str) => Multiplier * str.Length;

  ModifiesFuncB(int multiplier)
  {
    Multiplier = multiplier;
  }

  IFuncB Modify(IFuncB funcB)
  {
    // This is pseudo-code.
    funcB.DoSomethingB = ModifiedDoSomethingB;
  }
}

Here is some sample code using the modifier to modify the behavior of the IFuncB interface on an object that implements it.

ImplementsAB myObj = new ImplementsAB();
ModifiesFuncB modifier = new ModifiesFuncB(2);

Console.WriteLine(myObj.DoSomethingA());        // Outputs 3.14
Console.WriteLine(myObj.DoSomethingB("hello")); // Outputs 5

myObj = modifier.Modify(myObj);

Console.WriteLine(myObj.DoSomethingA());        // Outputs 3.14
Console.WriteLine(myObj.DoSomethingB("hello")); // Outputs 10

Is there a solution, software design pattern, or common method of doing this? This could be the entirely wrong way to things but demonstrating what I should do instead would be a great help. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire