匿名类实例放置

时间:2015-07-20 20:37:43

标签: java coding-style sun-coding-conventions

你在哪里放置匿名类的实例?

public class MyClass {
    // Variables
    private Api api;

    // Functions
    public void callApi() {
        api.get(<...>, responseListener)
    }

    // Where to put that? Top of the file, bottom, next to function?
    private ResponseListener responseListener = new ResponseListener() {
        @Override
        public void onSuccess(Object response) {
        }
    };
}

而且,在这种情况下,最好是直接在api调用中实例化吗?

    public void callApi() {
        api.get(<...>, new ResponseListener() {
            @Override
            public void onSuccess(Object response) {
            }
        });
    }

1 个答案:

答案 0 :(得分:1)

这是你做出的决定。你最初编写它的方式,你有一个名为responseListener的字段,它被初始化一次并在每次callApi()调用时重用。如果这是您想要的行为,您可以将其置于callApi()方法之上(使用其他字段api)。或者把它放在原处。他们都很好,你喜欢哪一个。

但是,如果每次调用callApi()时都想要一个新实例,那么将它放在callApi()内是有意义的。

因此,无论您将其放在callApi()内还是外面都很重要,但只有您可以决定哪个更好。如果你想在外面,在外面的地方并不重要,只有你能决定哪个更好。

相关问题