当尝试采用使用匿名或嵌套类实现监听器的风格时,目的是为了隐藏通知方法以防止被用于除监听之外的其他用途(例如,我不希望任何人能够调用actionPerformed)。例如来自 Java ActionListener:implements vs anonymous class 的示例:
问题是是否有一种优雅的方法使用这个习语来删除监听器?我发现
为了被认为是相等的,监听器应该具有相同的外部this。要实现equals,我需要获取其他对象的外部this。所以它将变成这样(我觉得有点笨重):
public MyClass() {
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//doSomething
}
});
}
问题是是否有一种优雅的方法使用这个习语来删除监听器?我发现
ActionListener
的实例化不会每次产生相同的对象,因此Collection.remove()
将无法删除最初添加的对象。为了被认为是相等的,监听器应该具有相同的外部this。要实现equals,我需要获取其他对象的外部this。所以它将变成这样(我觉得有点笨重):
interface MyListener {
Object getOuter();
}
abstract class MyActionListener extends ActionListener
implement MyListener {
}
public MyClass() {
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// doSomething on MyClass.this
}
public Object getOuter() {
return MyClass.this;
}
public boolean equals(Object other)
{
if( other instanceof MyListener )
{
return getOuter() == other.getOuter();
}
return super.equals(other);
});
}
}
还是说我必须将ActionListener对象作为外部类的(私有)成员变量来保存?
equals()
方法使这些对象相等,对吧? - Alex Salauyou