繁体   English   中英

如何避免使用MVP方法在方法中传递大量参数

[英]How to avoid passing large number of arguments in method using MVP approach

我有一个包含大量注册字段的注册屏幕,并且当用户单击注册按钮时,我将字段值传递给演示者。 在演示者中,我验证这些值并创建一个对象。 问题是register()方法中有大量参数。 我认为我应该避免这种情况,但是我不知道如何去做。

也许您可以探索Builder模式 当您需要传递大量参数时,它可以使代码保持干净。 当您不知道将要传递的参数的确切数量时,它也非常有用,因为其中某些参数可能不是必需的。

在实践中,您会遇到类似

MyObject myObject
void register() {
    myObject = MyObject.Builder(<mandatory arguments>)
               .argument1(<argument 1>)
               .argument2(<argument 2>)
               ...
               .create();
    if (myObject == null) fail();
    else dosomething();
}

我以前做过的一种方法是在每个必须完成的字段上使用TextWatcher:

myEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        presenter.myEditTextChanged(s.toString());
    }
});

然后让演示者中的相应方法更新您的实体。 这样,当用户最终单击注册时,所有详细信息将已经在您的演示者中等待。

它还具有您可以在用户进行过程中进行验证的优势-即直到所有字段都有效后才启用注册按钮。

如果您使用的是ButterKnife,RxBinding或DataBinding,则代码也更加简洁。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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