gpt4 book ai didi

c# - "Classes should never perform work involving Dependencies in their constructors."

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:27 24 4
gpt4 key购买 nike

因此,引用来自 "Dependency Injection in .NET" .考虑到这一点,下面的类是否设计错误?

class FallingPiece { //depicts the current falling piece in a tetris game
private readonly IPieceGenerator pieceGenerator;
private IPiece currentPiece;

public FallingPiece(IPieceGenerator pieceGenerator) {
this.pieceGenerator = pieceGenerator;
this.currentPiece = pieceGenerator.Generate(); //I'm performing work in the constructor with a dependency!
}

...
}

所以这个 FallingPiece 类负责控制俄罗斯方 block 游戏中当前下落的棋子。当棋子撞到底部或其他地方时,引发一个事件信号,然后通过工厂生成另一个新棋子,它再次从上方开始下落。

我看到的唯一选择是使用一个 Initialize() 方法来生成该片段,但在我看来,这有点违背让构造函数将您的对象置于有效状态的想法。

最佳答案

一般来说,经验法则就是:经验法则。不是人们永远不应该偏离的不变法则——我敢肯定,您会发现在构造函数中使用依赖项进行操作比其他方式更有意义的情况。

考虑到这一点,让我们重新审视您的特定设计:

So this FallingPiece class has the responsability of controlling the current falling piece in a tetris game. When the piece hits the bottom or some other place, raises an event signaling that and then, through the factory, generates another new piece that starts falling again from above.

我觉得 FallingPiece 在完成后触发片段生成器似乎很奇怪。

我会这样设计:

class PieceGenerator
{
public FallingPiece NextFallingPiece()
{
FallingPiece piece = new FallingPiece(NextPiece());
return piece;
}
// ...
}

class GameEngine
{
public PieceGenerator pieceGenerator = new PieceGenerator();

public void Start()
{
CreateFallingPiece();
}

void CreateFallingPiece()
{
FallingPiece piece = pieceGenerator.NextFallingPiece();
piece.OnStop += piece_OnStop;
piece.StartFalling();
}

void piece_OnStop(FallingPiece piece)
{
piece.OnStop -= piece_OnStop;
if (!GameOver())
CreateFallingPiece();
}
}

至少在这个设计中,GameEngine 完全负责告诉 Generator 何时创建它的棋子,这似乎比具有该职责的 FallingPiece 更符合习惯。

关于c# - "Classes should never perform work involving Dependencies in their constructors.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3577626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com