これは、関係が存在する可能性はあるが、関係には必須ではないためです。
例:
まず、Command
インターフェースがあります
public interface Command {
void execute();
}
いくつかの実装で...
public class CopyFilesCommand implements Command {
@Override
public void execute() {
// copy some files
}
}
public class ZipFilesCommand implements Command {
@Override
public void execute() {
// collect the copied files to a zip archive
}
}
public class MailZipFileCommand implements Command {
@Override
public void execute() {
// mail the zip file to some address
}
}
ここで、基本構成のサーバー アプリケーションを想像してください。
public class Config {
private static final Config INSTANCE = new Config();
private List<Command> commands = new ArrayList<>();
private Config() {
// intentionally empty
}
public static List<Command> getCommands() {
return Collections.unmodifiableList(INSTANCE.commands);
}
public static void addCommand(Command command) {
INSTANCE.commands.add(command);
}
}
クライアントメソッドは、このように構成をセットアップできるようになりました
public class Client {
public void setUpConfig() {
Config.addCommand(new CopyFilesCommand());
Config.addCommand(new ZipFilesCommand());
Config.addCommand(new MailZipFileCommand());
}
}
サーバーアプリケーション内で実行されているサービスは、コマンドを受け取って呼び出すことができます
public class Invoker implements Runnable {
@Override
public void run() {
for (Command command : Config.getCommands()) {
command.execute();
}
}
}
Client と Invoker はお互いを認識していません (つまり、関係はありません) が、両方が知っているコマンドを使用して連携しています。