2

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

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) {
            }
        });
    }
4

1 回答 1

1

这是你必须做出的决定。按照您最初编写的方式,您有一个名为的字段,该字段responseListener被初始化一次并在每次callApi()调用时重用。如果这是您想要的行为,您可以将它放在callApi()方法之上(使用另一个字段,api)。或者把它留在原处。两个都可以,看你喜欢哪个。

但是,如果您希望每次callApi()调用一个新实例,那么将它放在callApi().

所以不管你把它放在里面callApi()还是外面都很重要,但只有你才能决定哪个更好。如果你想要它在外面,外面在哪里都没有关系,同样只有你可以决定哪个更好。

于 2015-07-20T21:24:02.987 回答