0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Template Methodパターン

Posted at

1. Template Method パターンとは?

  • 定義: アルゴリズムの骨組みを定義し、一部のステップをサブクラスに委譲するデザインパターン
  • 目的: 共通の処理を親クラスで定義し、詳細を子クラスでカスタマイズ
  • カテゴリ: 振る舞いパターン(Behavioral Pattern)

2. どんな時に使う?

  • アルゴリズムの構造は同じだが、一部の処理を変更したい場合
  • コードの重複を避けたい場合
  • サブクラスで特定のステップをカスタマイズしたい場合

3. 構造

  • AbstractClass: テンプレートメソッドと抽象メソッドを定義
  • ConcreteClass: 抽象メソッドを実装

4. サンプルコード(Java)

ドキュメント生成プロセスの例。

// AbstractClass
abstract class DocumentGenerator {
    // テンプレートメソッド
    public void generateDocument() {
        openDocument();
        writeContent();
        closeDocument();
    }
    
    protected abstract void writeContent();
    
    private void openDocument() {
        System.out.println("Opening document");
    }
    
    private void closeDocument() {
        System.out.println("Closing document");
    }
}

// ConcreteClass
class PDFGenerator extends DocumentGenerator {
    protected void writeContent() {
        System.out.println("Writing PDF content");
    }
}

class WordGenerator extends DocumentGenerator {
    protected void writeContent() {
        System.out.println("Writing Word content");
    }
}

// クライアントコード
public class Main {
    public static void main(String[] args) {
        DocumentGenerator pdf = new PDFGenerator();
        pdf.generateDocument();
        
        DocumentGenerator word = new WordGenerator();
        word.generateDocument();
    }
}

5. メリット

  • コードの重複を削減
  • アルゴリズムの構造を一貫性のある形で提供
  • サブクラスでのカスタマイズが容易

6. デメリット

  • テンプレートメソッドの変更が難しい
  • サブクラスが増えると管理が複雑になる場合も

7. 実際の使用例

  • フレームワークの処理フロー(例:ServletのdoGet/doPost)
  • データ処理パイプライン(読み込み→処理→保存)
  • ゲームのメインループ(初期化→更新→描画)

8. まとめ

  • Template Methodパターンは、アルゴリズムの骨組みを固定しつつ詳細をカスタマイズする場合に有効
  • コードの重複を減らし、保守性を向上
  • テンプレートの設計時には柔軟性と拡張性を考慮!
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?