Menu
Coddy logo textTech

Commandパターン

CoddyのGOジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 91/107。

Command パターンはリクエストをオブジェクトとしてカプセル化し、操作のパラメーター化、キューへの追加、または取り消し機能のサポートを可能にします。Strategy がアルゴリズムをカプセル化するのに対し、Command はパラメーターとともにアクション全体をカプセル化します。

Goでは、Executeメソッドを持つCommandインターフェースを定義し、アクションの実行に必要なすべての情報を保持する具象コマンドを作成します。

type Command interface {
    Execute() string
}

type Light struct {
    IsOn bool
}

type TurnOnCommand struct {
    light *Light
}

func (c *TurnOnCommand) Execute() string {
    c.light.IsOn = true
    return "Light turned on"
}

type TurnOffCommand struct {
    light *Light
}

func (c *TurnOffCommand) Execute() string {
    c.light.IsOn = false
    return "Light turned off"
}

Invoker は、コマンドが何をするのかを知らずに、コマンドを格納して実行します。

type RemoteControl struct {
    command Command
}

func (r *RemoteControl) SetCommand(c Command) {
    r.command = c
}

func (r *RemoteControl) PressButton() string {
    return r.command.Execute()
}

Invoker は receiver(Light)から完全に切り離されています。

light := &Light{}
remote := &RemoteControl{}

remote.SetCommand(&TurnOnCommand{light: light})
fmt.Println(remote.PressButton())  // ライトがオンになった

remote.SetCommand(&TurnOffCommand{light: light})
fmt.Println(remote.PressButton())  // ライトがオフになった

Command は、操作を保存、遅延、または再実行する必要がある場合の undo/redo システム、タスクキュー、またはマクロ記録の実装に最適です。

challenge icon

チャレンジ

簡単

Command パターンを使って、Undo 機能付きのテキストエディターを構築しましょう!テキスト操作を encapsulates するコマンドを作成し、エディターでアクションを実行したり元に戻したりできるようにします。これは、コマンドがなぜ非常に強力なのかを示す典型的なユースケースです。

コードを次の 3 つのファイルに整理します。

  • command.go: コマンドインターフェースと、具体的なテキスト編集コマンドを Define します。

    2 つのメソッドを持つ Command インターフェースを作成します。アクションを実行する Execute() string と、アクションを元に戻す Undo() string です。

    *TextEditor に対して操作を行う 2 種類のコマンドを Implement します。

    • InsertCommand: エディターのポインターと挿入するテキストを holds します。Execute はテキストをエディターの Content に追加し、Inserted: [text] を返します。Undo はそのテキストを末尾から削除し、Undone insert: [text] を返します。
    • DeleteCommand: エディターのポインターと、末尾から削除する characters の count を holds します。Execute はその characters を削除し(Undo 用に保存し)、Deleted: [removed text] を返します。Undo はそれらを復元し、Undone delete: [restored text] を返します。
  • editor.go: テキストエディター(receiver)と、コマンドの history を管理する invoker を Create します。

    Content field(string)と、Append(text string) および DeleteLast(count int) string(削除されたテキストを返す)メソッドを持つ TextEditor struct を構築します。

    実行されたコマンドのスライスを history として holds する EditorInvoker struct を構築します。次のメソッドを Add します。

    • ExecuteCommand(cmd Command) string: コマンドを executes し、それを history に追加して、結果を返します。
    • UndoLast() string: history から最後のコマンドを削除し、その Undo を呼び出して、結果を返します。history が empty の場合は、Nothing to undo を返します。
  • main.go: 一連の操作でコマンドシステムを実演します。

    操作の count を読み取ります。各操作について、操作タイプ(insertdelete、または undo)を読み取ります。insert の場合は、挿入するテキストも読み取ります。delete の場合は、characters の count を読み取ります。各操作を invoker 経由で Execute し、結果を出力します。すべての操作の後、最終的なエディターの Content を Final: [content] として出力します。

次の入力が提供されます。

  • 1 行目: 操作の Number
  • 各操作: 操作タイプ、必要に応じた追加データ(insert の場合はテキスト、delete の場合は count)

たとえば、次の入力が given された場合:

5
insert
Hello
insert
 World
delete
3
undo
undo

出力は次のようになります。

Inserted: Hello
Inserted:  World
Deleted: rld
Undone delete: rld
Undone insert:  World
Final: Hello

また、次の入力が given された場合:

4
insert
Go
insert
Lang
undo
insert
!

出力は次のようになります。

Inserted: Go
Inserted: Lang
Undone insert: Lang
Inserted: !
Final: Go!

また、次の入力が given された場合:

2
undo
insert
Test

出力は次のようになります。

Nothing to undo
Inserted: Test
Final: Test

各コマンドが、そのアクションを実行および逆転するために必要なすべてを encapsulates していることに注目してください。invoker はコマンドが何をするのかを知りません。単にそれらを Execute し、Undo をサポートするために history を管理します。

自分で試してみよう

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	
	// 操作の数を読み取る
	line, _ := reader.ReadString('\n')
	numOps, _ := strconv.Atoi(strings.TrimSpace(line))
	
	// editor と invoker を作成する
	editor := &TextEditor{}
	invoker := &EditorInvoker{}
	
	for i := 0; i < numOps; i++ {
		// 操作タイプを読み取る
		opLine, _ := reader.ReadString('\n')
		opType := strings.TrimSpace(opLine)
		
		var result string
		
		switch opType {
		case "insert":
			// 挿入するテキストを読み取る
			textLine, _ := reader.ReadString('\n')
			text := strings.TrimSuffix(textLine, "\n")
			
			// TODO: InsertCommand を作成し、invoker を通じて実行する
			_ = text
			_ = editor
			
		case "delete":
			// 削除する文字数を読み取る
			countLine, _ := reader.ReadString('\n')
			count, _ := strconv.Atoi(strings.TrimSpace(countLine))
			
			// TODO: DeleteCommand を作成し、invoker を通じて実行する
			_ = count
			
		case "undo":
			// TODO: invoker で UndoLast を呼び出す
			
		}
		
		fmt.Println(result)
	}
	
	// 最終コンテンツを出力する
	fmt.Printf("Final: %s\n", editor.Content)
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Goオンラインコンパイラ