的Java / Android的:匿名本地类名为VS班 [英] Java/Android: anonymous local classes vs named classes

查看:142
本文介绍了的Java / Android的:匿名本地类名为VS班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下什么是对使用匿名类与命名的内部类的好的做法呢?

I would like to ask what is the good practice on using anonymous classes vs. named inner classes?

我写一个Android应用程序,其中包括许多UI元素(按钮,文本框等)。对他们来说,我需要某种形式的听众,所以在的onCreate 应用程序我有一堆相当小匿名类的,如:

I am writing an Android application, which includes many UI elements (buttons, text fields, etc). For many of them I need some kind of listeners, so in onCreate of the application I have bunch of quite small anonymous classes like:

someButton.setOnClickListener(
    new View.OnClickListener() {
        public void onClick(View v) {
            // do something...
        }
    }
);

每一个这样的匿名类的是5 - 20行大 - 足够小和果壳中的的书从的 Java™的建议适合好:

Each of of such anonymous class is 5 - 20 lines big - small enough and fits good for recommendations from Java™ in a Nutshell book:

在一般情况下,你应该考虑使用本地类,如果一个匿名类来代替:

In general, you should consider using an anonymous class instead of a local class if:

      
  • 类有一个很短的身体。
  •   
  • 类只有一个实例是必要的。
  •   
  • 类是用它定义之后。
  •   
  • 类的名称不会使你的code变得更容易理解。
  •   
  • The class has a very short body.
  • Only one instance of the class is needed.
  • The class is used right after it is defined.
  • The name of the class does not make your code any easier to understand.

不过问题,国际海事组织,是的onCreate 变得相当大,在code变得更加复杂阅读和快速寻找到它理解。它仍然是很容易理解的,但太大了。

But the problem, IMO, is that onCreate becomes quite big and the code becomes more complex to read and understand by quick looking in to it. It is still easy to understand, but simply too big.

那么,这将是在这种情况下,更好的做法? - 有一堆小内的子类,其中每个被很好地分开了,但只使用一次或更好的继续使用匿名类来代替

So what would be better practice in such case - have bunch of small inner sub-classes, where each of it is nicely separated , but used just once or better keep using anonymous classes instead?

推荐答案

我不认为这是一个明确的答案的一种方式或其他。这两种风格做工精细,它真的只是你preFER。

I don't think there is a clear answer one way or the other. Both styles work fine, its really just what you prefer.

另一种选择是有

每一个的onClick通过一个函数调用,这将保持匿名类很短的内容。即:

the contents of each onClick by a single function call, which will keep the anonymous classes very short. I.e:

someButton.setOnClickListener(
    new View.OnClickListener() {
        public void onClick(View v) {
            doSomeButtonClick();
        }
    }
);


private void doSomeButtonClick() {
  // do something
}

这篇关于的Java / Android的:匿名本地类名为VS班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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