jeudi 31 janvier 2019

Command Pattern + MVP - Access Data In Presenter From A Command (Design Problem)

I'm having a problem in the design of my application. I have a few commands which one of them needs to access a Dictionary (commands) within the presenter that holds the list of commands in order to show the user the list of all available commands. My question is, what is a good design solution to tackle this problem? I really don't want to make the commands field static or DI the presenter inside the command, would appreciate your help, thanks.

Form1Presenter.cs:

    private Dictionary<string, ICommand> commands { get; }

    public Form1Presenter(IForm1View form1View)
    {
        this.commands = new Dictionary<string, ICommand>();

        var commands = Program.container.GetAllInstances<ICommand>();
        foreach (ICommand command in commands)
        {
            this.commands.Add(command.Name, command);
            command.Completed += Command_Completed;
        }
    }



public class HelpCmd : ICommand
{
    public string Name => "/help";

    public string Description => "List of available commands.";

    public event EventHandler<CommandResult> Completed;

    private readonly StringBuilder commandsStr;

    public HelpCmd()
    {
        commandsStr = new StringBuilder();
        foreach (ICommand command in placeholder) // <---- Access dictionary here
        {
            commandsStr.AppendLine(command.ToString());
        }
    }

    public void Execute(object parameter)
    {
        var cmdInfo = parameter as CommandInfo;

        var info = new CommandResult
        {
            Message = cmdInfo.Message,
            Text = commandsStr.ToString(),
            SendType = SendType.Text
        };

        Completed?.Invoke(this, info);
    }

    public override string ToString()
    {
        return $"*{Name}* - {Description}";
    }
}

1 commentaire: