如何避免创建仅由Java中的内类引用的对象?
我正在尝试使用内部类创建一些系统。我的代码可以汇总到类似的内容。
public abstract class A {
public abstract void doSomething();
}
public class B {
public final ArrayList<A> list=new ArrayList<A>();
public B(){
}
}
public class C {
private int i;
public C(B b){
b.list.add(new A(){
public void doSomething(){
i++;
}
});
b.list.add(new A(){
public void doSomething(){
System.out.println(i);
}
});
}
}
public static void main (String[] arg) {
B manager=new B();
new C(manager);
new C(manager);
new C(manager);
}
一个是抽象类,将以内在类的继承(在我的原始代码中是侦听器类),b是某种管理列表的管理类别,并且c保留数据的数据应仅通过其内部进行修改或读取类并在初始化时,它将A添加到B类B中。代码本身正常工作。但是问题是因为会有各种C2,C3这样的c可以做不同的事情,这会导致我的代码被成千上万个未分配的对象new C(Manager);
coppers; 这使调试变得更加困难代码看起来真的很丑陋。因此,在我看来,首先我的方法是错误的,但不知道如何避免这种情况。那么,我应该如何将自己的方法更改为没有成千上万个未分配的对象呢?
I'm trying to create some system with inner class. My code can be summarized to something like this.
public abstract class A {
public abstract void doSomething();
}
public class B {
public final ArrayList<A> list=new ArrayList<A>();
public B(){
}
}
public class C {
private int i;
public C(B b){
b.list.add(new A(){
public void doSomething(){
i++;
}
});
b.list.add(new A(){
public void doSomething(){
System.out.println(i);
}
});
}
}
public static void main (String[] arg) {
B manager=new B();
new C(manager);
new C(manager);
new C(manager);
}
A is abstract class that will be inherited as inner class (in my original code it is listener class), B is some kind of manager class that hold list of As, and C hold data it's data should be only modified or read by it's inner class and upon initialization it add A to the class B. Code itself works fine. But problem is as there will be various kinds of C something like C2, C3 that does different thing and this leads to my code overwhelmed with thousands of unassigned object new C(manager);
this make debugging extra hard and code looks really ugly. So it seems to me my approach in the first place was wrong but have no idea how to avoid this. So how should I change my approach to not have thousands of unassigned objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的建议是:尽量不要使用构造函数进行依赖状态的操作(
i
)。使用静态功能,并将状态保存在单独的类中(我们称其为“上下文”)。My suggestion is: try not to use constructors to do operations that depend on state (
i
). Use static functions, and save the state in a separate class (we call it a “context”).