I’m using this pattern for the first time, and using C#.
I just wanted to check that this is the correct implementation.
I have a button on a Winform, and when clicked on that will output some data in a particular format, defined by choosing from a drop down box. Now this may change in the future, hence me using the Strategy pattern to encapsulate what changes.
I have a ‘Strategy Interface’ that simply exposes a single method: “Display Data()”.
On my button click I use the following code:
private void ConfirmButton_Click(object sender, EventArgs e)
{
IViewData viewData;
switch (outputMedia)
{
case "Excel":
viewData = new ExcelOutput(operation, study);
viewData.DisplayData();
break;
case "Spotfire":
viewData = new SpotfireOutput(operation, study);
viewData.DisplayData();
break;
}
}
Is this an acceptable way to use this pattern? Obviously if additional output media is identified then I will simply create a new subclass and add an extra ‘case’ on the switch statement.
Thanks.
The proper way to use Strategy would be to separate the creation of the
IViewDataobject from its usage. The creation itself might be handled by a Factory Method. Then you can use the createdIViewDatain a separate location, which is totally unaware of the object’s concrete class.E.g.
Now, from this, you can improve the solution further by refactoring the Factory Method. You may decide to use a
Dictionaryinstead of aswitch, or to create the view data objects only once and cache them, or (as you suggested) replacing it with dependency injection …