Design Patterns

Pattern 21 sur 23, famille Comportement

Template Method

En français : Patron de méthode

Définir le squelette d'un algorithme dans une classe de base, en laissant les sous-classes redéfinir certaines étapes sans changer sa structure.

Le problème

Importer du CSV, du JSON ou de l'Excel suit toujours les mêmes étapes : ouvrir, parser, valider, sauvegarder. Seul le parsing change, mais chaque importeur duplique tout le reste.

La solution

Écrire une méthode « template » (run()) qui enchaîne les étapes dans un ordre figé. Les étapes variables sont abstraites ; les étapes optionnelles sont des « hooks » avec un comportement par défaut.

Le pattern en action

  • Client
  • Rôle clé du pattern
  • Objet
  • Données ou état
  1. run() enchaîne les étapes dans un ordre figé. Étape commune : open().
  2. parse() est abstraite : elle dépend du format.
  3. La sous-classe CsvImporter fournit sa propre implémentation.
  4. validate() est un hook : comportement par défaut, redéfinissable.
  5. save() est commune. Seul le format change, tout le reste est réutilisé.

Une analogie

Un plan de maison standard : fondations, murs, toit sont imposés, mais chaque client choisit son carrelage et ses fenêtres.

Quand l'utiliser

  • Algorithmes avec structure fixe et étapes variables
  • Frameworks : cycles de vie (setUp/tearDown, hooks)
  • Imports / exports multi-format

Avantages et limites

Avantages

  • Élimine la duplication
  • Ordre des étapes garanti
  • Points d'extension clairs

Limites

  • Basé sur l'héritage (rigide)
  • Le squelette peut contraindre les sous-classes
  • Violation de Liskov possible si un hook est mal redéfini

Implémentations

Le même exemple, écrit de façon idiomatique dans chaque langage.

Template Method en Python

template-method.py 35 lignes
import csv
import json
from abc import ABC, abstractmethod


class DataImporter(ABC):
    def run(self, path: str) -> None:          # la méthode template
        raw = self.open(path)
        rows = self.parse(raw)
        rows = [r for r in rows if self.validate(r)]
        self.save(rows)

    def open(self, path: str) -> str:
        with open(path, encoding="utf-8") as f:
            return f.read()

    @abstractmethod
    def parse(self, raw: str) -> list[dict]: ...

    def validate(self, row: dict) -> bool:     # hook : redéfinition optionnelle
        return bool(row.get("email"))

    def save(self, rows: list[dict]) -> None:
        print(f"{len(rows)} lignes importées")


class CsvImporter(DataImporter):
    def parse(self, raw): return list(csv.DictReader(raw.splitlines()))


class JsonImporter(DataImporter):
    def parse(self, raw): return json.loads(raw)


CsvImporter().run("clients.csv")

Template Method en TypeScript

template-method.ts 26 lignes
import { promises as fs } from "node:fs";

type Row = Record<string, string>;

abstract class DataImporter {
  // méthode template
  async run(path: string) {
    const raw = await this.open(path);
    const rows = this.parse(raw).filter((r) => this.validate(r));
    await this.save(rows);
  }

  protected open(path: string) { return fs.readFile(path, "utf8"); }

  protected abstract parse(raw: string): Row[];

  protected validate(row: Row) { return Boolean(row.email); } // hook

  protected async save(rows: Row[]) { console.log(rows.length + " lignes importées"); }
}

class JsonImporter extends DataImporter {
  protected parse(raw: string): Row[] { return JSON.parse(raw); }
}

await new JsonImporter().run("clients.json");

Template Method en Java

template-method.java 29 lignes
abstract class DataImporter {

    // final : les sous-classes ne peuvent pas changer l'ordre des étapes
    public final void run(Path path) throws IOException {
        String raw = Files.readString(path);
        List<Map<String, String>> rows = parse(raw).stream()
                .filter(this::validate)
                .toList();
        save(rows);
    }

    protected abstract List<Map<String, String>> parse(String raw);

    protected boolean validate(Map<String, String> row) {      // hook
        return row.get("email") != null;
    }

    protected void save(List<Map<String, String>> rows) {
        System.out.println(rows.size() + " lignes importées");
    }
}

class CsvImporter extends DataImporter {
    @Override
    protected List<Map<String, String>> parse(String raw) {
        /* découpage lignes / colonnes */
        return List.of();
    }
}

Template Method en C#

template-method.cs 23 lignes
abstract class DataImporter
{
    public async Task RunAsync(string path)            // template (non virtual)
    {
        var raw = await File.ReadAllTextAsync(path);
        var rows = Parse(raw).Where(Validate).ToList();
        Save(rows);
    }

    protected abstract IEnumerable<Dictionary<string, string>> Parse(string raw);

    protected virtual bool Validate(Dictionary<string, string> row) =>   // hook
        row.ContainsKey("email");

    protected virtual void Save(List<Dictionary<string, string>> rows) =>
        Console.WriteLine($"{rows.Count} lignes importées");
}

class JsonImporter : DataImporter
{
    protected override IEnumerable<Dictionary<string, string>> Parse(string raw) =>
        JsonSerializer.Deserialize<List<Dictionary<string, string>>>(raw)!;
}

Template Method en PHP

template-method.php 29 lignes
abstract class DataImporter
{
    final public function run(string $path): void      // méthode template
    {
        $raw = file_get_contents($path);
        $rows = array_filter($this->parse($raw), fn(array $r) => $this->validate($r));
        $this->save($rows);
    }

    abstract protected function parse(string $raw): array;

    protected function validate(array $row): bool       // hook
    {
        return !empty($row['email']);
    }

    protected function save(array $rows): void
    {
        echo count($rows), ' lignes importées', PHP_EOL;
    }
}

final class JsonImporter extends DataImporter
{
    protected function parse(string $raw): array
    {
        return json_decode($raw, true, flags: JSON_THROW_ON_ERROR);
    }
}

Template Method en Go

template-method.go 30 lignes
// Go n'a pas d'héritage : le squelette reçoit l'étape variable via une interface
type Parser interface {
    Parse(raw []byte) ([]map[string]string, error)
}

func RunImport(path string, p Parser) error {
    raw, err := os.ReadFile(path)
    if err != nil {
        return err
    }
    rows, err := p.Parse(raw)
    if err != nil {
        return err
    }
    valid := rows[:0]
    for _, r := range rows {
        if r["email"] != "" {
            valid = append(valid, r)
        }
    }
    fmt.Println(len(valid), "lignes importées")
    return nil
}

type JSONParser struct{}

func (JSONParser) Parse(raw []byte) (rows []map[string]string, err error) {
    err = json.Unmarshal(raw, &rows)
    return
}

Questions fréquentes

Qu'est-ce que le design pattern Template Method ?

Définir le squelette d'un algorithme dans une classe de base, en laissant les sous-classes redéfinir certaines étapes sans changer sa structure. Écrire une méthode « template » (run()) qui enchaîne les étapes dans un ordre figé. Les étapes variables sont abstraites ; les étapes optionnelles sont des « hooks » avec un comportement par défaut.

Quand utiliser le pattern Template Method ?

Algorithmes avec structure fixe et étapes variables ; Frameworks : cycles de vie (setUp/tearDown, hooks) ; Imports / exports multi-format.

Quels sont les avantages et les inconvénients du pattern Template Method ?

Avantages : Élimine la duplication ; Ordre des étapes garanti ; Points d'extension clairs. Limites : Basé sur l'héritage (rigide) ; Le squelette peut contraindre les sous-classes ; Violation de Liskov possible si un hook est mal redéfini.