Mehrdad Kamelzadeh
Mehrdad Kamelzadeh

Reputation: 1784

Best way of implementing Strategy Pattern

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)?

Upvotes: 1

Views: 2174

Answers (4)

mostafa kazemi
mostafa kazemi

Reputation: 565

u can use "dynamic" in c# instead like this:

Method(dynamic input)

Method(DTO1 input) Method(DTO2 input) Method(DTO3 input)

Upvotes: 0

Kaveh Shahbazian
Kaveh Shahbazian

Reputation: 13513

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.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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;
}

Upvotes: 0

Oscar
Oscar

Reputation: 13960

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.

Upvotes: 0

Related Questions