你被困在大多数以 MVVM 开始的程序员都被困住的地方。你只看 MVVM 并严格忽略其他一切。
您看到的是:Model、ViewModel 和 View,您尝试将所有业务逻辑放入其中之一。
但是Model 部分不仅仅是带有一点逻辑的 POCO 对象。服务也属于模式。这是您封装所有不属于某个模型的业务逻辑的地方。
您可以实现一个PostService 类和一个CommentService 类,它们都实现了UpVote/DownVote 功能并从您的ViewModel 调用这些服务。
public interface ICommentService
{
void UpVote(Post post, Comment comment);
void DownVote(Post post, Comment comment);
}
public class CommentRestService
{
IRestClient client;
public CommentRestService(IRestClient client)
{
this.client = client;
}
public void UpVote(Post post, Comment comment)
{
var postId = post.Id;
var commentId = comment.Id;
var request = ...; // create your request and send it
var response = request.GetResponse();
// successfully submitted
if(response.Status == 200)
{
comment.VoteStatus = VoteType.Up;
comment.Score += 1;
}
}
public void DownVote(Post post, Comment comment)
{
var postId = post.Id;
var commentId = comment.Id;
var request = ...; // create your request and send it
var response = request.GetResponse();
// successfully submitted
if(response.Status == 200)
{
comment.VoteStatus = VoteType.Down;
comment.Score -= 1;
}
}
}
在您的 ViewModel 中,您只需通过依赖注入传递服务或通过 ServiceLocator 获取它,然后使用它的方法,而不是在模型上调用 UpVote/DownVote。
// in ViewModel
// get via ServiceLocator or DI
ICommentService commentService = ...;
commentService.UpVote(this.Post, this.SelectedComment);
您也可以在模型上实现此方法,将操作封装到 Comment 类中,即通过将 Score 和 VoteStatus 设为“私有集;”
public class Comment
{
public string Comment { get; set; }
public Post Post { get; private set; }
public VoteType VoteStatus { get; private set; }
public int Score { get; private set; }
public void UpVote(ICommentService commentService)
{
// for this you'd change your Up/Vote method to return only true/false and not
// change the state of your model. On more complex operation, return an CommentResult
// containing all necessary information to update the comment class
if(commentService.UpVote(this.Post, this))
{
// only update the model, if the service operation was successful
this.Score++;
this.VoteStatus = VoteType.Up;
}
}
}
并通过调用它
SelectedComment.UpVote(commentService);
首选后一种方法,因为您可以更好地控制Comment 对象,并且Comment 的状态只能通过Comment 及其方法类进行修改。这可以防止在代码中的其他地方意外更改此值并接收不一致的状态(即更改 VoteStatus 而不增加 Score 值)。