1

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

4

4 回答 4

2

它将生成更易于维护的代码来将您的策略​​和上下文定义为接口:

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

我自己更喜欢构造函数注入。但在这种情况下,需要进行属性注入,因为可能需要在运行时更改策略。

现在您可以实现/注入您的具体类型。

于 2013-06-11T15:24:05.050 回答
0

您可以使用构造函数注入。

public class MyClass{

public MyClass(Motor motor){
       this.motor = motor;
   }

}

然后,由您的 IOC 容器来提供所需的依赖项。

于 2013-06-11T15:17:28.943 回答
0

当然,有很多可能性。战略工厂呢?

this.motor = MotorFactory.newMotor(MotorFactory.BOOST);

或者只是一个用于注入的突变方法(假设IMotor是电机的抽象接口:)

void setMotor(IMotor m) {
    this.motor = m;
}
于 2013-06-11T15:17:35.020 回答
0

你可以在 C# 中使用“动态”,而不是像这样:

方法(动态输入)

方法(DTO1 输入) 方法(DTO2 输入) 方法(DTO3 输入)

于 2020-08-07T14:43:51.143 回答