【发布时间】:2018-03-07 10:12:50
【问题描述】:
我在为我的 MVVM 项目设计良好的架构时遇到了问题。 我想出了类似下面的东西,请阅读并告诉我这是错误的方法还是好的: 我会有一些界面:
public interface ISomeStrategy
{
void LoadData();
void Search(string text);
IList<SomeObject> SomeObjectsList { get; set; }
}
还有一个实现这个接口的类:
public class FirstStrategy: INotifyPropertyChanged, ISomeStrategy
{
public CompositePayslipItem(IDataService dataService)
{
DataService = dataService;
}
private IDataService DataService;
public IList<SomeObject> SomeObjectList{get; set;}
public async void LoadData()
{
SomeObjectList =await DataService.GetAll();
}
public async void Search(string text)
{
SomeObjectList =await DataService.GetByKey(text);
}
}
和 ViewModel:
public void SomeViewModel
{
public SomeViewModel(IDataService dataService)
{
Strategy = new FirstStrategy(dataService);
Strategy.LoadData();
}
public ISomeStrategy Strategy {get; set;}
private Command<string> searchCommand;
public Command<string> SearchCommand => searchCommand?? (searchCommand= new Command(ExecuteSearchCommandAsync));
private async void ExecuteSearchCommandAsync(string text)
{
Strategy.Search(text);
}
}
如您所见,所有逻辑都将位于“策略”类中,这些类将通过 ViewModel 绑定到 View。它给了我什么?我可以在运行时动态更改实现。例如,如果我有一个 Employee 和 Manager,其中搜索和获取数据的逻辑不同,我可以只实现另一个类并更改属性 ISomeStrategy Strategy 而无需编辑 Employee 的现有代码(在很多方法中没有额外的 if)。 不幸的是,它存在一些问题:
- 所有绑定(命令除外)都将在 *Factory 类中,这可能会产生误导
- 在大多数情况下,一台 VM 将有一个策略实现,因此会有大量代码无用。另一方面,将来客户可以要求另一个角色(实现),并且会更容易(只需实现另一个类 - 无需编辑旧代码)。
你怎么看?或者,也许您使用其他模式进行业务逻辑?
编辑: Xaml 部分:
<ContentPage
x:Class="Test.SomePage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<StackLayout>
<SearchBar
HeightRequest="50"
SearchCommand="{Binding SearchCommand}" />
<ListView
x:Name="formatsList"
Margin="0"
ItemsSource="{Binding Strategy.SomeObjectList}">
</StackLayout>
</ContentPage>
【问题讨论】:
-
你能用 XAML/Binding 部分更新你的问题吗?
-
我添加了 XAML 部分
-
啊,我明白您对宝贵评论的看法。在这种情况下,我不太理解您的第一个问题:所有绑定(命令除外)都将在 *Factory 类中,这可能会产生误导
-
理论上,当他在 ViewModel 中看到命令正常但其他绑定绑定到一个大对象时,他可能会感到困惑。仅此而已。
-
这个帖子是关于如果这个解决方案没有违反“规则”或者对未来可能加入项目的开发人员来说过于误导
标签: c# mvvm xamarin.forms