[英]How to avoid passing large number of arguments in method using MVP approach
I have a registration screen with large number of registration fields, and when user click register button, I pass field values to presenter. 我有一个包含大量注册字段的注册屏幕,并且当用户单击注册按钮时,我将字段值传递给演示者。 In presenter I validate these values and create an object.
在演示者中,我验证这些值并创建一个对象。 The problem is a large number of arguments in register() method.
问题是register()方法中有大量参数。 I think that I should avoid this situation, but I have no idea how to do it.
我认为我应该避免这种情况,但是我不知道如何去做。
Maybe you could explore the Builder pattern . 也许您可以探索Builder模式 。 It allows to keep the code clean when you need to pass a big number of arguments.
当您需要传递大量参数时,它可以使代码保持干净。 It's also very useful when you don't know the exact number of arguments that will be passed, because some of them might not be mandatory.
当您不知道将要传递的参数的确切数量时,它也非常有用,因为其中某些参数可能不是必需的。
In practice, you would have something like 在实践中,您会遇到类似
MyObject myObject
void register() {
myObject = MyObject.Builder(<mandatory arguments>)
.argument1(<argument 1>)
.argument2(<argument 2>)
...
.create();
if (myObject == null) fail();
else dosomething();
}
One way I have done this previously is to use a TextWatcher on each field that has to be completed: 我以前做过的一种方法是在每个必须完成的字段上使用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());
}
});
Then have the corresponding methods in the presenter update your entity. 然后让演示者中的相应方法更新您的实体。 This way when the user finally clicks register all the details will already be waiting in your presenter.
这样,当用户最终单击注册时,所有详细信息将已经在您的演示者中等待。
It also has the advantage that you can do validation as the user progresses - ie the register button isn't enabled until all fields are valid. 它还具有您可以在用户进行过程中进行验证的优势-即直到所有字段都有效后才启用注册按钮。
If you are using ButterKnife, RxBinding or DataBinding the code is more succinct as well. 如果您使用的是ButterKnife,RxBinding或DataBinding,则代码也更加简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.