Best way of implementing Strategy Pattern - c#

I have been looking for Strategy Pattern and I saw This link which the guy has explained this pattern very well.
But as far as I know (maybe right or wrong) you shouldn't make a new class in another class (for the sake of being loosely coupled).
this.motor = new Motor(this)
Is there a better kind of implementation for that to not violate the principles (like IoC)?

It would produce a more maintainable code to define both your strategy and context as interfaces:
interface IStrategy<T> where T : IContext
{
T Context { get; }
void Execute();
}
// this cab have other structures too depending on your common logic
// like being generic
interface IContext
{
}
I, myself prefer constructor injection. But in this case property injection is needed because one may need to change the strategy at run time.
Now you can implement/inject your concrete types.

You can use Constructor Injection.
public class MyClass{
public MyClass(Motor motor){
this.motor = motor;
}
}
Then, it's up to your IOC container to supply the needed dependency.

Sure, there are many possibilities. What about a strategy factory?
this.motor = MotorFactory.newMotor(MotorFactory.BOOST);
or simply a mutator method for injection (assuming IMotor is the abstract interface for motors:)
void setMotor(IMotor m) {
this.motor = m;
}

u can use "dynamic" in c# instead like this:
Method(dynamic input)
Method(DTO1 input) Method(DTO2 input) Method(DTO3 input)

Related

C# - use dependency injection (ninject) instead of factory pattern

I have read a lot about this topic, but couldn't grasp it all the way.
I am trying to use the Ninject.Extensions.Factory instead of my factory to create new objects depending on user input. I want to fully use the Ninject functionality and the IoC concept.
Now the code looks like this:
interface IFeatureFactory
{
IFeature createFeature(int input);
}
and:
class BasicFeatureFactory : IFeatureFactory
{
public IFeature createFeature(int input)
{
switch (input)
{
case 1:
return new FirstFeature();
case 2:
return new SecondFeature();
default:
return null;
}
}
}
In the future, the IFeature will have dependencies so I want to do it the IoC way.
EDIT:
consumer class - the IFeatureFactory and IUILayer are injected into the FeatureService constructor and resolved using Ninject.
private IFeatureFactory featureFactory;
private IUILayer uiHandler;
public FeatureService(IFeatureFactory featureFactory, IUILayer uiHandler)
{
this.featureFactory = featureFactory;
this.uiHandler = uiHandler;
}
public void startService()
{
int userSelection = 0;
uiHandler.displayMenu();
userSelection = uiHandler.getSelection();
while (userSelection != 5)
{
IFeature feature = featureFactory.createFeature(userSelection);
if (feature != null)
{
IResult result = feature.execFeature();
uiHandler.displayResult(result);
}
else
{
uiHandler.displayErrorMessage();
}
uiHandler.displayMenu();
userSelection = uiHandler.getSelection();
}
}
and IFeature class:
public interface IFeature
{
IResult execFeature();
}
Bindings:
public override void Load()
{
Bind<IFeatureFactory>().To<BasicFeatureFactory>();
Bind<IUILayer>().To<ConsoleUILayer>();
}
How can I convert this Factory Pattern to IoC with the Ninject.Extensions.Factory? keep in mind the creation of the IFeature is dependent on the user input.
To me it is look like you have 2 options to refactor your code to get the full benefits of ninject.
The way you're working now is no different than pure di (which there is nothing wrong about it and it is better it some cases) but as you said you want to fully use ninject functionality.
Option one
Instead of injecting IFeatureFactory into FeatureService inject the interface IFeatureProvider which will look like this:
public interface IFeatureProvider
{
IFeature GetFeature(int featureType);
}
Now your FeatureService will get the requested features from this provider instead of the factory.
You will need to implement IFeatureProvider and for that you will need 2 more interfaces IFirstFeatureFactory and ISecondFeatureFactory:
public interface IFirstFeatureFactory
{
IFeature CreateFirstFeature();
}
public interface ISecondFeatureFactory
{
IFeature CreateSecondFeature();
}
And now IFeatureProvider impelementaion:
public class FeatureProvider: IFeatureProvider
{
private readonly IFirstFeatureFactory _firstFeatureFactory;
private readonly ISecondFeatureFactory _secondFeatureFactory;
public FeatureProvider(IFirstFeatureFactory firstFeatureFactory, ISecondFeatureFactory secondFeatureFactory)
{
_firstFeatureFactory=firstFeatureFactory;
_secondFeatureFactory=secondFeatureFactory;
}
public IFeautre GetFeature(int featureType)
{
switch(featureType)
{
case 1:
return _firstFeatureFactory.CreateFirstFeature();
case 2:
return _secondFeatureFactory.CreateSecondFeature();
default:
return null;
}
}
}
the thing you should notice that i just extract the object who is responsible for the 'new' into another interface.
We will not implement the two factory interfaces as ninject will do it for us if we will bind it properly.
The binding:
Bind<IFeature>().ToFeature<FirstFeature>().NamedLikeFactoryMethod((IFirstFeatureFactory o) => o.CreateFirstFeature());
Bind<IFeature>().ToFeature<SecondFeature>().NamedLikeFactoryMethod((ISecondFeatureFactory o) => o.CreateSecondFeature());
Bind<IFirstFeatureFactory>().ToFactory();
Bind<ISecondFeatureFactory>().ToFactory();
Bind<IFeatureProvider>().To<FeatureProivder>();
This 'NameLikeFactoryMethod' binding is equivalent the using of named binding as i did here and it is now the recommended way by ninject for factories.
The importent thing to notice here you do not implement IFirstFeatureFactory and ISecondFeatureFactory by yourself and you're using ninject functionallity for that.
The major disadvantage of this option is when we need to add more features we will need to create except for the feature itself another FeatureFactory and also change the FeatureProvider to handle it as well.
If the features are not changed very often this option can be good and simple but if they do it can become maintenance nightmare and that is why i suggest option 2.
Option two
In this option we will not create any provider class at all and will put all the creation logic inside the factory.
IFeatureFactory interface will look pretty similar to the one you have now, but instead of using an int as parameter we will use a string (is will suit better with the named binding as we will see soon).
public interface IFeatureFactory
{
IFeature CreateFeature(string featureName);
}
We will not implement this interfaces by ourselves and let ninject do it for us, however we will need to tell ninject to use the first parameter of CearteFeature to detect which implementation to instantiate(FirstFeatue or SecondFeature).
For that we will need custom instance provider with this behavior as the StandardInstanceProvider using other convention to choose which implementation to instantiate(the default convention in this article).
Fortunately ninject show as exactly how we can implement it very quickly by UseFirstArgumentAsNameInstanceProvider.
Now the binding:
Bind<IFeature>().To<FirstFeature>().Named("FirstFeature");
Bind<IFeature>().To<FirstFeature>().Named("SecondFeature");
Bind<IFeatureFactory>().ToFactory(() => new UseFirstArgumentAsNameInstanceProvider());
The things to notice here:
We will not implement the factory interface by ourselves.
We are using named binding for each implementation and we will get the implementation from the factory according to the featureName we will pass to the factory method (this is why i prefer the parameter to be string).
Notice that if you pass feature name that is not "FirstFeature" or "SecondFeature" exception will be thrown.
We are using UseFirstArgumentAsNameInstanceProvider as our instance provider for our factory as mentioned before.
This has solved the problem in the first option as if we want to add new feature we well just need to create it and bind it to his interface with his name.
Now the client of the factory can ask from the factory feature with this new name without the need of changes in other classes.
Conslucsion
By choosing one of this options above over pure di we will get the benefits of letting ninject kernel create our object in the factories instead of doing all the 'new' on our own.
Although there is nothing wrong about not using IoC container this can really helps us in cases there is a big dependencies graph inside IFeature implementations as ninject will inject them for us.
By doing one of this options we are fully using ninject functionality without using a 'Service locator' which is considered as an anti pattern.
You can inject the features into the BasicFeatureFactory's constructor.
class BasicFeatureFactory : IFeatureFactory
{
FirstFeature feature1;
SecondFeature feature2;
public BasicFeatureFactory(FirstFeature feature1, SecondFeature feature2) {
this.feature1 = feature1;
this.feature2 = feature2;
}
public IFeature createFeature(int input) {
switch (input) {
case 1: return this.feature1;
case 2: return this.feature2;
default: return null;
}
}
}

Apply SOLID Principle to basic app

Hi i am trying to apply the SOLID Principle to my code until i came across the interface and Dependency Inversion.
i am just having trouble with the constructor of FlightValidator class.
please can do advice?enter code here
you can get the full project here: https://www.sendspace.com/file/zk022f
i am confused on this class. in how do i create an instance of it?
public class FlightValidator
{
private IValidator _validator;
private GeneralFlightValidation _generalFlightValidation;
private BasicFlightValidation _basicFlightValidation;
private int flightRuleType;
public FlightValidator(IValidator _validator,
int flightRuleType
)
{
this._validator = _validator;
this.flightRuleType = flightRuleType;
}
public void GetFlightRule(ScheduledFlight scheduledFlight)
{
switch(this.flightRuleType)
{
case (short)FlightRuleType.STANDARD:
{
this._validator.FlightValidator(scheduledFlight);
break;
}
case (short)FlightRuleType.BASIC:
{
this._validator.FlightValidator(scheduledFlight);
break;
}
default:
{
this._validator.FlightValidator(scheduledFlight);
break;
}
}
}
}
public enum FlightRuleType : int
{
STANDARD,
BASIC
}
i am confused on this class. in how do i create an instance of it?
You can just pass the dependency to the constructor:
IValidator validator = ...
FlightValidator flightValidator = new FlightValidator(validator);
or, if you're using an IoC container (e.g. Unity):
FlightValidator flightValidator = container.Resolve<FlightValidator>();
Anyway, I find your code a bit confusing. Your FlightValidator class depends on an IValidator, which itself has a FlightValidator method (very bad name for a method by the way)... So what is the FlightValidator class good for, if it just calls another thing that does the flight validation?
What you're looking at here is Dependency Injection. The general idea is to remove the dependency from the class and injecting said dependency via the constructor. This allows your class to have less responsibilities, promotes re-use, which results in a more agile solution.
To instantiate this class, you can use poor man's dependency injection, like this:
IValidator myValidator = new SomeValidator();
FlightValidator flightValidator = new FlightValidator(myValidator, 69);
For a more elegant approach, you can use Inversion of Control.

Is this a valid Decorator pattern example

Is this a valid example for decorator pattern?
I would like to know is this example a valid example for decorator pattern? if not what
is correction or change needed here, please suggest.
We have a Container class representing container and for it i want to add features at
run time. features like wheel and lid are used in the example.
Client code:
private void button2_Click(object sender, EventArgs e)
{
IContainer container = new MovableConatiner(new Container());
string features = container.getFeatures();
container = new LidConatiner(container);
features = container.getFeatures();
}
API code:
public interface IContainer
{
string getFeatures();
}
public class Container : IContainer
{
public string getFeatures()
{
return "Container";
}
}
// a decorator to add wheels
public class MovableConatiner : IContainer
{
protected IContainer container;
public MovableConatiner(IContainer container)
{
this.container = container;
}
public string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format("{0} , four wheels", features) :
features;
return features;
}
}
// a decorator to add lid to contaner
public class LidConatiner : IContainer
{
protected IContainer container;
public LidConatiner(IContainer container)
{
this.container = container;
}
public string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format("{0} , Lid", features) :
features;
return features;
}
}
its as per my understand so i would like to verify my understanding.
While your implementation doesn't ideally reflects the structure or the Decorator pattern, from my point of view it solves the same problem that Decorator is targeted to solve. Your solution is just not as strict and safe for future modifications as "ideal" Decorator implementation.
You simplified implementation removing "unnecessary" for you abstractions. But while you might think they are unnesessary at the moment, they will become very useful in the future when your application grows and get few dozens of components and decorators. it's easy to get lost who is who currently.
In the link I provided there is very simple description of main participants of the Decorator pattern, and there is a sample code, very similar to yourth, but complete. I won't copy-paste it here to show you corrent implementation.
I just want to stress that if you don't understand the need of some abstractions in Design patterns, you better leave them, or read once more how to use it instead of just removing them.
UPDATE: point in favour of abstractions:
All common logic must be implemented in one place and reused. Code duplication is very-very bad. I think everybody agrees that this is fundamental principle of well-organized code.
Now let's analyze your implementation of Decorator pattern without extracting abstract base class for decorators. Compare the implementation of your MovableContainer and LidContainer classes - do you see anything similar? I hardly see any difference at all actually. Ok, let's find what's common:
both have constructors, receiving component to decorate.
both store reference to IContainer which is decorated
both retrieve component's features in the getFeatures() method
both check component's features for empty and if not - append some string (the only difference is string itself)
All this logic should be extracted to base class. You already should udnerstand that base class for your two decorators is required.
Let's go further. Let's imagine every possible decorator for every possible container. As implies from the Decorator pattern definition, it's obvious that some logic is common for all decorators: they all store reference to the decorating object. Is that enough for extracting base class (single property - that's not hard to copy-paste it to both decorators you have)? Definitely enough!
If you like real-life examples, here it is. You've implemented few decorators, let's say 100 (2 is still enouth, 100 just exadurates the problem). And they you realize that some decelopers doesn't know how to use them properly - they just pass NULLs to your decorators. Their code works fine, then created decorators are passed somewhere else, or stored to DB etc. And then at some magical points, your code is failing in various places later. It's hard to every time find where that NULL came from, which part of application created such object. You decide to add NULL-check in the constructor to disallow passing NULLs and make initial code fail to immediately fix the problem. Ouch, we need to fix all 100 constructors! And merge your changes with changes of 10 more developers who are working everybody on his decorator. That's not a good perspective.
If this example didn't convince you and you are still ready to copy-paste code 100 times, imagine that you are developing a reusable library and other developers from other companies also implement decorators derived from your IContainer. You have no way to fix constructors of their decorators and ensure they won't provide you with invalid object containint NULL internally. On contrary if you had a base class for Decorator, you just needed to fix it - and all implementations both yourth and 3rd party get that functionality. If you think you don't implement a reusable library - consider other developers working in your team as 3rd party - it's always useful and not so different - don't require them to change their code because you need some fix.
Finally I provide the way I would refactor your code (I didn't want to do it at the beginning to let you come to this on your own):
public interface IContainer
{
string getFeatures();
}
public class Container : IContainer
{
public string getFeatures()
{
return "Container";
}
}
public abstract class ContainerDecorator : IContainer
{
protected IContainer container;
protected ContainerDecorator(IContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public abstract string getFeatures();
}
public class StringFormatDecorator : ContainerDecorator
{
private readonly string _format;
public StringFormatDecorator(IContainer container, string format) : base(container)
{
_format = format;
}
public override string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format(_format, features) : features;
return features;
}
}
// a decorator to add wheels
public class MovableConatiner : StringFormatDecorator
{
public MovableConatiner(IContainer container) : base(container, "{0} , four wheels")
{
}
}
// a decorator to add lid to contaner
public class LidConatiner : StringFormatDecorator
{
public LidConatiner(IContainer container) : base(container, "{0} , Lid")
{
}
}
Such code not only improves core reuse, but also prevents others from using your decorators in wrong way because of lost border between containers and decorators. It's much harder to declare parameterless decorator now and almost impossible to use it. You can't "decorate" one container with another container which is non-sense, but possible in your implementation when some new developer creates his own container without knowing your initial intentions.
Now doing things wrong becomes much more complex.

Data encapsulation consideration for method parameters (dependency injection)

I have a spec translator, like below.
//all specifications implement this base class
public abstract class SpecBase
{
public abstract void Translate(IContext context);
}
//spec translator implementation
public interface ISpecTranslator
{
void Translate(IContext context);
}
I need to inject the dependency of the SpecTranslator constructor. I have two ways to express the depenency.
Solution 1
public class SpecTranslator:ISpecTranslator
{
IList<SpecBase> specs;
public SpecTranslator(IList<SpecBase> specs)
{
this.specs = specs;
}
}
Please note using IList<SpecBase> works for now, but seems solution 2 provides more protection.
Solution 2:
public class SpecTranslator:ISpecTranslator
{
ISpec spec;
public SpecTranslator(ISpec spec)
{
this.spec = spec;
}
}
public interface ISpec
{
IList<SpecBase> specs {get;}
}
However, the implementation of ISpec have the same problem when using constructor dependency injection.
Any idea on pros and cons on these two solutions, or other solutions?
It seems in order to "translate" (analyze) the list of specs, the contents of the ISpec instance given need to be destructured in all cases. A list has to be obtained and seen through. No matter how many layers of abstraction you weave in, the SpecTranslator will finally need a list.
In your case I'd think of ISpec as a factory. If the list is not lazily calculated there is no value in it.
Also, simplicity is an important design principle. As ISpec does not add any capability or architectural freedom it does not carry its own weight.

What is the design pattern in this code?

Say I have a singleton-ish, factory-ish, reflection-ish class that receives some input, and spits back a new instance of a concrete implementation of some interface. What kind of design is this? Is there a better way to do what I want?
Here's some code to illustrate the point:
using System;
using System.Collections.Generic;
// static factory class
public static class ArticleFactory
{
// given an SKU, store the Type object for an IArticle object
private static Dictionary<string, Type> articleRegistry = new Dictionary<string, Type>();
// allow public registration of SKU-to-Type object relationships
public static bool Register(string sku, Type typeInfo)
{
if(!articleRegistry.ContainsKey(sku))
{
articleRegistry.Add(sku, typeInfo);
return true;
}
return false;
}
// given a SKU, give me an instance of the related IArticle object
public static IArticle NewArticle(string sku)
{
if(articleRegistry.ContainsKey(sku))
{
// use reflection to invoke the default constructor
return articleRegistry[sku].GetConstructor(Types.EmptyTypes).Invoke(null) as IArticle;
}
return null;
}
}
// example concrete-implementation of an IArticle
public class Jeans : IArticle
{
public decimal GetPrice() { return SomeDecimal(); }
}
// WHERE DO I CALL THIS LINE?
ArticleFactory.Register("0929-291", typeof(Jeans));
// Later on, if another group needs to write the class for Snowboards,
// how can they self-register their class, without changing any "Main()"
// or "Page_Init()" function?
Looks like you've already identified the pattern. It's the Factory Method Pattern. Or rather, a somewhat half-baked implementation of one. A slightly better approach would be to first make it an interface:
public interface IArticleFactory
{
IArticle CreateArticle(string sku);
}
Then implement the factory without any Reflection at all:
public class MyArticleFactory
{
private Dictionary<string, Func<IArticle>> instantiators =
new Dictionary<string, Func<Iarticle>>();
public MyArticleFactory()
{
Register("Jeans", () => new Jeans());
Register("Shirt", () => new Shirt());
// etc.
}
public IArticle CreateArticle(string sku)
{
Func<IArticle> instantiator;
if (creators.TryGetValue(sku, out instantiator))
return instantiator();
throw new UnknownSkuException(sku);
}
protected void Register(string sku, Func<IArticle> instantiator)
{
creators.Add(sku, instantiator);
}
}
A few important differences:
Registration isn't public, nor should it be. Registration usually either resides in a configuration file somewhere or is private.
Does not require the IArticle concrete types to have a default parameterless constructor. This can easily register articles with parameterized constructors (as long as it knows what parameters to use).
Throws an exception on duplicate registrations. I don't like the idea of simply returning false; if you try to register the same factory method twice, that ought to be considered a bug.
It's not static. You can replace this factory with a different factory. You can unit-test it.
Of course, an even better approach would just be to use any of the myriad of existing .NET Dependency Injection/Inversion of Control Frameworks, such as Ninject or AutoFac.
I don't know if it has a "name" as such, but it looks like some kind of manual service resolver. The problem I can see (from experience, sadly) is that it is inflexible in real terms, in that:
the registration only has a single configuration
it is hard to unit test
Personally I'd look at an IoC container if I was doing this in a new system; the IoC can handle this relationship, and provide a lot more capabilities for free (lifetimes, enrichment, extra setup, etc), and solve many associated problems.
BTW, it may be easier to:
return Activator.CreateInstance(articleRegistry[sku]);
I think what you're doing here is basically Dependency Injection (or Inversion of Control is what the cool kids call it). Have a look at these links:
Explanation from Wikipedia: http://en.wikipedia.org/wiki/Dependency_Injection
Two DI .Net frameworks:
StructureMap: http://structuremap.sourceforge.net/QuickStart.htm
Castle Windsor: http://www.castleproject.org/container/index.html
It's just a factory pattern that happens to use reflection in its implementation. Rather than using reflection, though, it would probably be more efficient to simply put instances of factory classes directly in the dictionary, though this might require some boilerplate code.

Categories