I’m developing a library in which I have two groups of classes:
A) a couple of classes with a bunch of functions, or “actions”, already written in code
B) a few classes which must be “configured” when instantiated, in a way that the user using my library can instantiate objects from this second group of classes and “assign” actions from the first group
Right now I’m using delegates, like this:
Somwhere in the code I declare some delegates that are used by A and B:
public delegate void Action03(int value);
Then I have the “actions” implemented in the group A:
public Delegates.Action03 DoSomething03 = delegate(int value) { [code to execute when this action is specified on the constructor] };
And finally we use constructors like the following to instantiate objects from group B, where we pass as arguments the delegates/actions that we want:
public SomethingGroupB(Delegates.Action03 act03) { ... }
So of course, we can instantiate objects passing delegates as arguments:
SomethingGroupB somthg1 = new SomethingGroupB(GrpA01.DoSomething03);
But the whole point is that we can instantiate similar objects but assigning different actions:
SomethingGroupB somthg2 = new SomethingGroupB(GrpA07.DoSomething03);
SomethingGroupB somthg3 = new SomethingGroupB(GrpA01.DoSomething01);
SomethingGroupB somthg4 = new SomethingGroupB(GrpA02.DoWhatever);
So… as a summary, I want to have pre-coded (in my library) actions, and the user must choose the actions assigned to a new object when it is instantiated, and those actions don’t change.
I guess I could also do it with events, but I don’t need to add and remove “actions”, they are fixed for the whole life of each object of type B.
So my question is: is there a better, nicer, cleaner solution than this one I’ve implemented with delegates?
Thank you very much!
The one improvement I would suggest would be to use the delegates defined in the framework, and not define your own. For example, your
Action03delegate is just aSystem.Action<int>. This would provide a bit more usability in terms of making the API more discoverable.That being said, this is effectively using delegates to implement the Strategy pattern. Provided this provides the full functionality you need, it is potentially a good option here, and rather clean.