c# – “类不应该在构造函数中执行涉及依赖关系的工作.”

所以,报价来自“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课程有责任控制当前的坠子在tetris游戏.当这件作品撞到底部或其他地方时,会发出一个事件,发出一个信号,然后通过工厂生成另一个新的部分,从上面开始下降.

我看到的唯一的替代方法是使用一个可以生成该片段的Initialize()方法,但是IMO与使构造函数将对象置于有效状态的想法相反.

最佳答案
一般来说,经验法则是:经验法则.不可变的法律,不应该从不偏离 – 我相信你会发现在你的构造函数中依赖关系做事情比其他事情更有意义的情况.

考虑到这一点,让我们回顾一下您的具体设计:

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完全负责告诉发电机什么时候创建它的作品,这似乎比FallingPiece有这个职责更惯性.

转载注明原文:c# – “类不应该在构造函数中执行涉及依赖关系的工作.” - 代码日志