简体   繁体   English

良好实践 - 在实例上传递实例和调用方法

[英]Good Practice - Passing instance and call methods on instance

I would like to bounce something off you guys. 我想从你们身上反弹一些东西。

In my Mobile App, I have a lot of Activity and Fragment classes and many of them contain a method or two with code for uploading images to a WebAPI 2.0 web service etc. etc. Sorry, just for info. 在我的移动应用程序中,我有很多Activity和Fragment类,其中许多包含一个方法或两个代码,用于将图像上传到WebAPI 2.0 Web服务等等。抱歉,仅供参考。

Now, I thought about creating a new class (eg ServiceController) and then move all the Service Calls to this new class. 现在,我考虑创建一个新类(例如ServiceController),然后将所有服务调用移动到这个新类。 The problem is, each one for the methods contain code for displaying a ProgressBar and hiding a ProgressBar, and let the activity continue to a next one, etc. etc. 问题是,方法的每一个都包含用于显示ProgressBar和隐藏ProgressBar的代码,并让活动继续到下一个,等等。

Now, is it good practice to pass an instance of the Activity that is calling the method in the ServiceController to the method in the ServiceController and then for instance do this: 现在,将ServiceIntroller中调用方法的Activity实例传递给ServiceController中的方法然后执行以下操作是不错的做法:

public static void uploadImages(Activity activity) { new BaseAsyncTask() { ... ... activity.hideProgressBar(); public static void uploadImages(Activity activity){new BaseAsyncTask(){... ... activity.hideProgressBar(); ... } ...}

PS: Specifically the "activity.hideProgressBar();" PS:特别是“activity.hideProgressBar();” above. 以上。

Thanks and have fun, Pieter 彼得,谢谢,玩得开心

There are many ways of decoupling between the classes , First of all service calls shouldn't be in the activity 有许多方法可以在类之间进行解耦,首先,服务调用不应该在活动中

first solution 1) Create one interface which contains onsuccess , onfailure abstract methods , and the parameters for that methods will be respective data model class types 2) The above interface should be implemented by activity which is dependent of data from server .In these implementation the showing and hiding progress bar , populating UI with data takes place 3)As you said ,Service Controller Instance will be created , while creating the instance of Service controller we have pass the reference of the interface . 第一个解决方案 1)创建一个包含onsuccess,onfailure抽象方法的接口,并且该方法的参数将是各自的数据模型类类型2)上述接口应该由依赖于来自服务器的数据的活动实现。在这些实现中显示和隐藏进度条,用数据填充UI 3)正如你所说,将创建服务控制器实例,同时创建服务控制器的实例我们已经传递了接口的引用。 these interface is used for communication between service controller and activity. 这些接口用于服务控制器和活动之间的通信。

second solution 第二解决方案

Use Event Bus For Communicating between service controller and Activity OTTO EVENT BUS i will prefer these . 使用事件总线在服务控制器和活动OTTO EVENT BUS之间进行通信我会更喜欢这些。

Let me know if you have any queries , I Hope these will solve your problem. 如果您有任何疑问,请告诉我,我希望这些可以解决您的问题。

third solution 第三种方案

use MVP Pattern Refer MVP Architecture Tutorial Best solution of all 使用MVP模式参考MVP架构教程最佳解决方案

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

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