Strategy Pattern- Correct Implementation

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.

-------------Problems Reply------------

The proper way to use Strategy would be to separate the creation of the IViewData object from its usage. The creation itself might be handled by a Factory Method. Then you can use the created IViewData in a separate location, which is totally unaware of the object's concrete class.

E.g.

private IViewData CreateViewData()
{
IViewData viewData;

switch (outputMedia)
{
case "Excel":
viewData = new ExcelOutput(operation, study);
break;
case "Spotfire":
viewData = new SpotfireOutput(operation, study);
break;
}
return viewData;
}

...

private void ConfirmButton_Click(object sender, EventArgs e)
{
IViewData viewData = CreateViewData();

viewData.DisplayData();
}

Now, from this, you can improve the solution further by refactoring the Factory Method. You may decide to use a Dictionary instead of a switch, or to create the view data objects only once and cache them, or (as you suggested) replacing it with dependency injection ...

First of all you can move viewData.DisplayData(); out of the switch. No need to repeat it for each case. And being able to call DisplayData in the same way for all of them is the whole point you introduced that interface in the first place.

Passing in the parameters in the same way in every case looks a bit repetitive too. So perhaps use a Dictionary<string,Func<Operation,Study,IViewData>> instead. But if different classes require different constructors this isn't going to work.

You should move the switch statement into its own method, ideally on some controller class. This means you dont have to re-write the switch code again when you need an IViewData object.

private void ConfirmButton_Click(object sender, EventArgs e)
{
IViewData viewData = ViewDataController.GetViewDataController(outputMedia, operation, study);

viewData.DisplayData();

}

And then in your controller:

public class ViewDataController
{
public static IViewData GetViewDataController(string outputMedia, string operation, string study)
{
IViewData viewData = null;

switch (outputMedia)
{
case "Excel":
viewData = new ExcelOutput(operation, study);
break;
case "Spotfire":
viewData = new SpotfireOutput(operation, study);
break;
}
return viewData;
}

This will allow you to reuse the same code throughout your application, and if you ever need to add any entries to the switch statement then you only have to do it in one place.

Category:c# Views:0 Time:2011-02-14

Related post

  • ViewHolder pattern correctly implemented in custom CursorAdapter? 2010-12-31

    Here is my custom CursorAdapter: public class TasksAdapter extends CursorAdapter implements Filterable { private final Context context; public TasksAdapter(Context context, Cursor c) { super(context, c); this.context = context; } /** * @see android.w

  • How to efficiently implement a strategy pattern with spring? 2010-12-29

    I have a web application developped in Java 1.5 with Spring framework. Application contains "dashboards" which are simple pages where a bunch of information are regrouped and where user can modify some status. Managers want me to add a logging system

  • Strategy pattern, is this correct 2012-02-17

    In the strategy pattern is it ok to only do some of the logic in the strategy and skill keep some on my own code, will it still be the strategy pattern? Example: i use the strategy pattern to influence how elements are ordered in my Doubly linked lis

  • Clean implementation of the strategy pattern in Perl 2008-09-16

    How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features. --------------Solutions------------- It really depends on what you mean by "clean implementation". As in any other languag

  • How to properly implement the Strategy pattern in a web MVC framework? 2009-04-27

    In my Django app, I have a model (lets call it Foo) with a field called "type". I'd like to use Foo.type to indicate what type the specific instance of Foo is (possible choices are "Number", "Date", "Single Line of Text", "Multiple Lines of Text", an

  • Would you implement a strategy pattern here and if yes, how? 2009-09-03

    Consider an application that generates production plans (simplified code sample below) . There's a big list of products and we call product.GetProductionTime() many times while doing complex calculations in the production plan. We need product.GetPro

  • Is Entity Framework ObjectContext correct implementation of Unit Of Work Pattern? 2010-06-25

    Entity Framework 4 - STE - simple DB with single table Blogs having BlogID PK column... var samplesDbEntities = new SamplesDBEntities(); var blogId = Guid.NewGuid(); samplesDbEntities.Blogs.AddObject(new Blog() { BlogID = blogId }); var objectSetResu

  • vb.net implement strategy pattern with different interface 2011-06-07

    is it possible to implement strategy pattern with different parameters in VB.net? For example I have the following code: Public Interface InterfaceDataManipulation Sub updateMyData() End Interface How to implemente updateMyData in the class that impl

  • How can we implement Strategy Pattern using AspectJ 2011-08-30

    Can I implement Strategy Pattern using AOP. I would like to either 1. Override the default algorithm 2. Or Would like to dynamically select any of the given algorithm. Thanks, --------------Solutions------------- Look at "AspectJ Cookbook" by Russell

  • What is the correct design pattern to implement email validation for each provider? 2012-05-01

    I have to validate email through several validators. I have class(EmailValidator) that has list of validators(RegexValidator, MXValidator...) and it validates email through that validators. RegexValidator, for example, has its own validators for each

  • How to properly implement the Strategy Pattern with two interfaces? 2012-04-09

    I have created a service data access layer where there are multiple databases where data needs to come from. I was doing fine with one database where I defined the memberRepository that contained member details. However, now I have to get session-rel

  • How does the Strategy Pattern work? 2008-09-18

    How does it work, what is it used for and when should one use it? --------------Solutions------------- Let's explain the strategy pattern the easy way: You have a class Car() with a method run(), so you use it this way in a pseudo language: mycar = n

  • Real World Example of the Strategy Pattern 2008-12-16

    I've been reading about the OCP principal and how to use the strategy pattern to accomplish this. I was going to try and explain this to a couple of people, but the only example I can think of is using different validation classes based on what statu

  • What is the difference between the template method and the strategy patterns? 2009-03-21

    Can someone please explain to me what is the difference between the template method pattern and the strategy pattern is? As far as I can tell they are 99% the same - the only difference being that the template method pattern has an abstract class as

  • String to Stategy in Strategy Pattern 2009-08-25

    I'm working in AS3, but I guess this could be a general question, so I'll frame it more vaguely... I'm using an XML file to define parameters for a particular class of object that implements the Strategy Pattern. There will be large variety of object

  • Factory & Strategy patterns 2009-09-30

    I need to create a class which will be responsible for result set processing but it might happen that different algorithms should be used to process that result set. I am aware of the following options: 1) Use Strategy patern, below is pseudo code: i

  • When and why should the Strategy Pattern be used? 2009-11-10

    When would the Strategy Pattern be used? I see client code snippets like this: class StrategyExample { public static void main(String[] args) { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrate

  • Strategy Pattern - multiple return types/values 2009-11-14

    We are working on an image processing project using C# and EmguCV. Our team is composed of 3 people. To make faster progress, the 3 of us work on different sub-problems or experiment with different algorithms at the same time. Currently each of us cr

  • Does this Java Strategy pattern have a redundant Context class? 2010-01-06

    The following code sample is an implementation of the Strategy pattern copied from Wikipedia. My full question follows it... The Wiki's main method: //StrategyExample test application class StrategyExample { public static void main(String[] args) { C

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.087 (s). 11 q(s)