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);
}
}
のみが必要であることがわかり、その関心をclass
実装して main に登録します。その後、イベントでメソッドが呼び出されます。FileChangeEventListener
FileChangeEventNotifyer
notify
ここには、よくある落とし穴がいくつかあります。1 つは、この実装では を使用しないためsynchronized
、イベントの発生時にクラスが登録されている場合、クラスが通知を見逃す可能性があることです。利点は、これがノンブロッキングであることです。したがって、ノンブロッキング コレクションとブロッキング コレクションのどちらが望ましいかは、あなた次第です。
また、登録済みのリスナーが後で登録解除されていることを確認する必要があります。そうしないと、リスナーが積み重なり、メモリリークが発生する可能性があります。
私はこれを単一のものとして実装FileChangeEvent
しましたType
-明らかに、親FileChangeEvent
クラスを持ち、それを型のサブクラスで拡張できます。繰り返しますが、それはあなたのニーズが何であるかによって異なります。
とにかく、これで始められるはずです。