异步编程的最佳实践 [英] Asynchronous programming best practices

查看:170
本文介绍了异步编程的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近写了我的第一个Android应用程序,这是大约8,000-10,000线code。有一件事,不断地阻碍了我的正常使用设计模式是Android的大量使用异步调用(打开的对话​​框中,活动等)。由于这个原因,我的code很快开始寻找意大利面条就好了,我终于开始不喜欢看某一类。

I have recently written my first Android app which was roughly 8,000-10,000 lines of code. One thing that continuously hindered my use of normal design patterns was android's heavy use of asynchronous calls (opening dialogs, activities, etc). Due to this, my code very quickly began looking "spaghetti" like, and I eventually started to dislike looking at certain classes.

有没有具体的设计模式,或者是将上述这些系统,任何人都建议编程方法?是否有书面管理异步code有什么建议?

Are there specific design patterns or programming methodologies which are for systems such as these that anyone would recommend? Are there any suggestions for writing manageable asynchronous code?

推荐答案

  • 使用全局变量

如果你不想弄乱你的code简单 Intent.putExtra()调用和管理的事情对每个唯一活动你必须在应用程序中使用全局变量。扩展应用程序和存储数据,你需要,只要你的应用程序是活的。要真正实现它,<一个href="http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables/708317#708317">use这个优秀的答案。这将使依赖之间的活动消失。例如,假设你在应用程序的生命周期中需要一个用户名为您的应用程序 - 这是一个很好的工具这一点。无需脏 Intent.putExtra()的电话。

If you do not want to mess up your code with simple Intent.putExtra() calls and manage this things for each unique Activity you'll have to use global variables within the application. Extend Application and store data that you need as long your application is alive. To actually implement it, use this excellent answer. This will make dependencies between activities disappear. For example, say that you need a "username" for your application during the application's life cycle - this is an excellent tool for just that. No need for dirty Intent.putExtra() calls.

  • 使用样式

做的第一个Android应用程序时,一个常见的​​错误是一个通常只是开始编写XML视图。该XML文件将(没有问题,非常快)上升到了code很多行。在这里,您可以在这里你只需要使用风格属性来实现特定行为的解决方案。例如,考虑这块code:

One common mistake when making the first Android application is that one usually just start writing the XML views. The XML files will (without problem and very fast) go up to very many lines of code. Here you can have a solution where you just use the style attribute to implement a specific behaviour. For example, consider this piece of code:

值/ styles.xml 的:

<style name="TitleText">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">#000</item>
    <item name="android:textStyle">bold</item>   
</style>

布局/ main.xml中的:

现在,如果你有,比方说,两个的TextView 和两者应该有相同的行为,让他们使用 TitleText 的风格。样品code:

Now, if you have, let's say, two TextViews and both of them should have the same behaviour, make them use the TitleText style. Sample code:

<!--- ... -->
<TextView
   android:id="@+id/textview_one"
   style="@style/TitleText" 
/>

<TextView
   android:id="@+id/textview_two" 
   style="@style/TitleText" 
/>
<!--- ... -->

简单,你不需要重复code。如果你真的想进一步看看在这个特别的主题,请看看布局技巧:创建可重用的UI组件

  • 使用字符串

这一点很短,但我认为提到它是非常重要的。另一个错误,开发人员可以做的是跳过的的strings.xml 的和只写用户界面消息(和属性名)内的code(在那里他将需要它)。为了使应用程序更易于维护;只是定义消息和属性的的strings.xml 的文件。

This point is short but I think it is important to mention it. Another mistake that developers might do is to skip the strings.xml and just write UI messages (and attribute names) inside the code (where he will need it). To make your application easier to maintain; just define messages and attributes in the strings.xml file.

  • 创建和使用一个全球性的工具类

当我写我的第一个应用程序,我只是写了(和重复),我需要它的方法。结果?有很多方法,这些方法有各种各样的活动之间的相同的行为。我的心得是做工具类。例如,假设你必须让所有的活动的Web请求。在这种情况下,跳过定义它们的实际活动内,做一个静态方法吧。样品code:

When I wrote my first application I just wrote (and duplicated) methods where I needed it. The result? A lot of methods that had the same behaviour between various activities. What I have learned is to make a tool class. For example, let's say you have to make web requests in all of your activities. In that case, skip defining them inside the actual Activity and make a static method for it. Sample code:

public final class Tools {

    private Tools() {
    }

    public static final void sendData(String url, 
              String user, String pass) {
        // URLConnections, HttpClients, etc...
    }

}

现在,你可以使用这个code以下在活动需要向服务器发送数据:

Now, you can just use this code below in your Activity that needs to send data towards a server:

Tools.sendData("www.www.www", "user", "pass");

不过,你明白了吧。使用这种模式的在你需要它的,它会阻止你搞乱你的code。

However, you get the point. Use this "pattern" where you need it, it will keep you from messing up your code.

  • 让我们自定义的类定义,用户需要与应用程序交互的行为

这可能是最有用的一点。如果只是定义的当用户需要与应用程序交互的假设你有一个菜单,它的行为是非常长的线方面,为什么我们保持菜单的计算,在同一个班?每个小项目将让你的活动类痛片$ C $了C更长 - 你的code看起来像面条。而不是有这样的事情。例如,:

This is probably the most useful point. To just define "where the user needs to interact with your application" let's say you have a Menu, which behaviour is very long in terms of lines, why do we keep the Menu's calculations in the same class? Every little item will make your Activity class a painful piece of code longer - your code look like "spaghetti". For example, instead of having something like this:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item;
    item = menu.findItem(R.id.menu_id_one);
    if (aBooleanVariable) {
        item.setEnabled(true);
    } else {
        item.setEnabled(false);
    }
    // More code...
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem i) {
    // Code, calculations...
    // ...
    // ...
    return super.onOptionsItemSelected(i);
}

它重新设计的东西是这样的:

redesign it to something like this:

private MyCustomMenuInstance mMenuInstance;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
    setContentView(R.layout.main);

    mMenuInstance = new MyCustomMenuInstance();
}  

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    mMenuInstance.onPrepareOptionsMenu(menu);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem i) {
    mMenuInstance.onOptionsItemSelected(i);
    return super.onOptionsItemSelected(i);
}

例如, MyCustomMenuInstance

public class MyCustomMenuInstance { 

    // Member fields..

    public MyCustomMenuInstance() {
        // Init stuff.
    }

    public void onPrepareOptionsMenu(Menu menu) {
        // Do things..
        // Maybe you want to modify a variable in the Activity 
        // class? Well, pass an instance as an argument and create
        // a method for it in your Activity class.
    }

    public void onOptionsItemSelected(MenuItem i) {
        // Do things..
        // Maybe you want to modify a variable in the Activity 
        // class? Well, pass an instance as an argument and create
        // a method for it in your Activity class.
    }

}

您看看这是怎么回事。您可以将此很多事情,例如的onClick onClickListener onCreateOptionsMenu ,名单很长。要了解更多的最佳实践,你可以看到从谷歌一些示例应用程序此处。寻找如何,他们已经在一个不错的和正确的方式实现的事情。

You see where this is going. You can apply this to many things, e.g. onClick, onClickListener, onCreateOptionsMenu, the list is long. To learn more "best practices" you can see some sample applications from Google here. Look for how they've implemented things in a nice and correct way.

最后一个字;保持你的code干净,命名以逻辑的方式,特别是在以正确的方式你的变量和方法。总是,总是知道你在哪里在code - 这是非常重要的。

Last word; keep your code clean, name your variables and methods in a logical manner and especially in a correct way. Always, always understand where you are in your code - that is very important.

这篇关于异步编程的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆