Home >Backend Development >C++ >Is Using Custom Delegates in an ICommand Implementation the Best Approach for Avoiding Repeated Instantiation?
ICommand implementation in MVVM: avoid repeated instantiation
Question:
To avoid repeatedly creating ICommand instances, I tried to implement an ICommand class using a custom delegate. This class contains two delegates: OnExecute
(void delegate, accepts object parameters) and OnCanExecute
(bool delegate, accepts object parameters).
The code is as follows:
<code class="language-csharp">public class TestCommand : ICommand { public delegate void ICommandOnExecute(object parameter); public delegate bool ICommandOnCanExecute(object parameter); private ICommandOnExecute _execute; private ICommandOnCanExecute _canExecute; public TestCommand(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod) { _execute = onExecuteMethod; _canExecute = onCanExecuteMethod; } //... }</code>
This approach works, but I have doubts about the plausibility of its implementation and whether there is a better way.
Solution:
This approach is very similar to the commonly used RelayCommand
pattern, RelayCommand
is a more mature and optimized solution.
RelayCommand implementation:
<code class="language-csharp">public class RelayCommand : ICommand { private readonly Predicate<object> _canExecute; private readonly Action<object> _execute; public RelayCommand(Predicate<object> canExecute, Action<object> execute) { _canExecute = canExecute; _execute = execute; } //... }</code>
Usage:
<code class="language-csharp">public class MyViewModel { private RelayCommand _doSomething; public ICommand DoSomethingCommand { get { return _doSomething ??= new RelayCommand( p => this.CanDoSomething(), p => this.DoSomeImportantMethod()); } } }</code>
Use null-coalescing assignment (??=
) to ensure that RelayCommand
instances are only created once.
Reference:
By using RelayCommand
or a similar pre-built implementation, you can avoid the additional complexity of custom delegates and get cleaner, more reliable code.
The above is the detailed content of Is Using Custom Delegates in an ICommand Implementation the Best Approach for Avoiding Repeated Instantiation?. For more information, please follow other related articles on the PHP Chinese website!