2

私はデザイン パターンを勉強していますが、コマンド パターンについて質問があります。これまでに見たすべてのクラス ダイアグラムの理由がわかりません (たとえば、これを見てください: http://en.wikipedia.org/wiki /Command_patternまたはhttp://www.oodesign.com/command-pattern.html ) は、クライアントが Invoker クラスのインスタンスを作成するため、Client と Invoker の間の関係を示しません。

前もって感謝します。

編集: Invoker をインスタンス化せず、具体的なコマンドとレシーバーの処理のみを担当する Client を実装する方法の簡単な例を誰かが投稿できますか?

4

1 に答える 1

1

これは、関係が存在する可能性はあるが、関係には必須ではないためです。

例:

まず、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 はお互いを認識していません (つまり、関係はありません) が、両方が知っているコマンドを使用して連携しています。

于 2013-10-30T12:06:59.760 に答える