c# - MVP中Presenter的实现问题

标签 c# .net oop mvp

所以..我打算使用 Model View Presenter(“被动”模式,在这种模式下 UI 非常愚蠢,并将所有事件发送给 Presenter,Presenter 负责处理模型)来粘合我域的业务逻辑和 UI。

我的问题是我的 Presenter 应该是什么样子。这就是我想要的吗?

public class TicTacToeGamePresenter
{
    private readonly ITicTacToeView view;
    private readonly PlayerController model;

    public TicTacToeGamePresenter(ITicTacToeView view) {
        this.view = view;
    }

    ...
}

我应该通过构造函数注入(inject)传递预期的 ITicTacToeView 实例吗?这将允许我将此 TicTacToeGamePresenter 类与 Forms、WPF、WebForms 等一起使用。我只需要确保我的 View 实现了 ITicTacToeView 接口(interface)。

或者我应该直接实例化我打算直接使用的具体类,并且只使用无参数构造函数吗?这似乎有点毫无意义,但我不得不问 :( .

我目前将 ITicTacToeView 接口(interface)定义为:

public interface ITicTacToePassiveView
{
    event EventHandler<EventArgs<Point>> ButtonClicked;
    void PlayerOPlayed(Point location);
    void PlayerXPlayed(Point location);
    void EnableStartButton();
    void DisableStartButton();
}

还有一件事。在编写 TicTacToeGamePresenter 的构造函数时,我得到了这个:

public TicTacToeGamePresenter(ITicTacToePassiveView view)
{
    this.view = view;

    IGameLogicAnaliser gameLogicAnaliser = new GameLogicAnaliser();
    IPlayer playerO = new Player(gameLogicAnaliser);
    IPlayer playerX = new Player(gameLogicAnaliser);

    Game game = new Game(playerO, playerX);

    this.playerOModel = new PlayerController(playerO, game);
    this.playerXModel = new PlayerController(playerX, game);
}

现在,在查看代码后,我认为通过为“上面的类”赋予类实例化的责任,让这个类的依赖关系变得更加明确可能会更好:

    public TicTacToeGamePresenter(ITicTacToePassiveView view, IPlayer playerO, IPlayer playerX, Game game, PlayerController playerOModel, PlayerController playerXModel)
    {
        this.view = view;
        this.playerO = playerO;
        this.playerX = playerX;
        this.game = game;
        this.playerOModel = playerOModel;
        this.playerXModel = playerXModel;
    }

哪个更好? 谢谢

最佳答案

我会选择您的第一个选项:使用构造函数将 View 注入(inject)演示者,因为它将允许您支持不同类型的 UI,前提是它们都实现了该接口(interface)。

此外,从单元测试的角度来看,您的生活会简单得多,因为任何实现该接口(interface)的模拟类都可以用于您的测试

编辑:添加了 WCSF 如何执行的代码示例 WCSF 使用依赖注入(inject),每个 View 都有一个注入(inject)到 View 中的演示者属性。这同样有效,不需要构造函数方法,但这需要公开一个公共(public) View 属性。

[CreateNew]
public DefaultViewPresenter Presenter
{
    set
    {
        this._presenter = value;
        this._presenter.View = this;
    }
}

关于c# - MVP中Presenter的实现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3483600/

相关文章:

.net - 如何将命令行参数传递给 ClickOnce 应用程序?

c# - 带有 CosmosDB 的 .NET Core 中的存储过程给出错误 500

php - 接口(interface)如何用于松散耦合?

c++ - 清理此代码 [文件输入]

c# - EF Core 左连接计数

c# - 如何在 C# 中使用线程池?

.net - 每个方法一个测试类?

oop - 这是一个贫血的领域模型吗?

c# - Visual Studio 2017 Mac上的SoundPlayer没有声音

c# - 从 C# 发送 html 电子邮件