回应 OP 的澄清评论:
对,这是观察者模式的一个简单示例:
public interface JNotifyListener {
void fileRenamed(int wd, String rootPath, String oldName, String newName);
void fileModified(int wd, String rootPath, String name);
void fileDeleted(int wd, String rootPath, String name);
void fileCreated(int wd, String rootPath, String name);
}
public enum Type {
RENAMED,
MODIFIED,
DELETED,
CREATED;
}
public class FileChangeEvent {
final Type type;
final int wd;
final String rootPath;
final String name;
final String newName;
public FileChangeEvent(Type type, int wd, String rootPath, String name, String newName) {
this.type = type;
this.wd = wd;
this.rootPath = rootPath;
this.name = name;
this.newName = newName;
}
public FileChangeEvent(Type type, int wd, String rootPath, String name) {
this(type, wd, rootPath, name, null);
}
public int getWd() {
return wd;
}
public String getRootPath() {
return rootPath;
}
public String getName() {
return name;
}
public String getNewName() {
return newName;
}
}
public interface FileChangeEventListener {
void notify(FileChangeEvent fileChangeEvent);
}
public class FileChangeEventNotifyer implements JNotifyListener {
final Collection<FileChangeEventListener> listeners = new ConcurrentLinkedQueue<FileChangeEventListener>();
@Override
public void fileRenamed(int wd, String rootPath, String oldName, String newName) {
notifyAll(new FileChangeEvent(Type.RENAMED, wd, rootPath, oldName, newName));
}
@Override
public void fileModified(int wd, String rootPath, String name) {
notifyAll(new FileChangeEvent(Type.MODIFIED, wd, rootPath, name));
}
@Override
public void fileDeleted(int wd, String rootPath, String name) {
notifyAll(new FileChangeEvent(Type.DELETED, wd, rootPath, name));
}
@Override
public void fileCreated(int wd, String rootPath, String name) {
notifyAll(new FileChangeEvent(Type.CREATED, wd, rootPath, name));
}
private void notifyAll(final FileChangeEvent changeEvent) {
for (final FileChangeEventListener changeEventListener : listeners) {
changeEventListener.notify(changeEvent);
}
}
public void registerListener(final FileChangeEventListener eventListener) {
listeners.add(eventListener);
}
public void unregisterListener(final FileChangeEventListener eventListener) {
listeners.remove(eventListener);
}
}
您可以看到 a class
only 需要实现FileChangeEventListener
并将其兴趣注册到 main FileChangeEventNotifyer
。然后它将notify
使用事件调用其方法。
这里有几个常见的陷阱。一个是这个实现不使用synchronized
,因此如果一个类在事件发生时被注册,它可能会错过一个通知。优点是这是非阻塞的。因此,由您决定是否最好使用非阻塞集合或阻塞集合。
此外,您要么需要确保所有已注册的侦听器事后都未注册,否则它们会堆积起来,最终可能导致内存泄漏。
我已经将它实现为一个单一FileChangeEvent
的Type
- 显然你可以有一个父FileChangeEvent
类,然后用类型的子类扩展它。同样,这取决于您的需求。
无论如何,这应该让你开始。