简体   繁体   中英

Command design pattern and user interaction

I am implementing command design pattern but my command needs to ask user for file name. I am not sure how can command ask for it?

The gang of four book seems to touch this issue but I am not quite clear. Below is my code (pseudo code to be correct and written on fly).

class OpenDocumentCommand : public Command
{
    virtual char * AskUserForFileName();
    virtual void Execute();

    Application _App;
}

void OpenDocumentCommand::Execute()
{
   char * fileName = AskUserForFileName();

   _App.OpenDocument( fileName );
}

Now in typical simple example, AskUserForFileName() can be cin and cout but how can it ask for file name in a proper Windows application? It should open File Explorer and user can select file name?

Does it means it has to be tighly coupled with windows? My plan is to use this code both on Windows and iOS so I would like a decoupled solution.

To minimize coupling between your command and the window you should at least insert an abstraction layer between them. In many MVVM implementations you can find a "Modal Dialog"-interface that hides the implementation details of the window from the calling ViewModel.

This interface contains at least a single method "ShowDialog()", but it can also take a ViewModel as a parameter and returns a callback to inform the caller when it gets closed by the user.

Here is an example:

public interface IModalWindow
2   {
3     bool? DialogResult { get; set; }
4     event EventHandler Closed;
5     void Show();
6     object DataContext { get; set; }
7     void Close();
8   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM