Working on WPF (UI programming) in C# I've started frequently injecting methods into the constructor of my view models.
For example:
public class HtmlRegexListViewModel : ViewModel
{
private readonly Action<HtmlRegex> onSelection;
public List<HtmlRegex> HtmlRegexes { get; private set; }
private HtmlRegex selected;
public HtmlRegex Selected
{
get { return selected; }
set
{
selected = value;
onSelection(value);
}
}
public HtmlRegexListViewModel(Action<HtmlRegex> onSelection, IDatabase database)
{
this.onSelection = onSelection;
HtmlRegexes = database.LoadHtmlRegexesVerySlowly();
}
}
Now I do this chiefly on view models because I don't want to go to the effort of creating an EventHandler and EventArgs derived pair of classes every time I want to tell the parent object that my state has changed.
However I also use this extensively elsewhere.
It seems like it's a style I'm going to regret when it comes to maintaining the code in future, but at the moment I can't think of many downsides. It decouples, preserves separation of concerns and is a nice way to make a class which has a single responsibility.
So is this a pattern (deferred double dispatch?), an anti-pattern or if it isn't, should it be?