🧩 Strategy Pattern
✅ Intent
- Externalize the varying part—the export behavior (strategy)—while keeping the shared
export()logic centralized - Maintain a simple structure by separating the output format logic into strategies
✅ Motivation
- Common behavior such as "start log" and "end log" is shared across all exporters
- The only difference is how the data is exported (PDF, CSV, XML)
- This combination of a shared workflow + interchangeable behavior is naturally handled using the Strategy pattern
✅ When to Use
- When multiple output formats or processing modes must be switched dynamically
- When output logic should be wrapped in a shared workflow (e.g., logging, formatting, templating)
- When new export formats are expected and the structure needs to support easy extension
- When part of the logic should be replaced (e.g., injecting mock logic in tests)
✅ Code Example
- TypeScript
- PHP
- Python
// Strategy インターフェース
interface ExportStrategy {
exportData(data: string): void;
}
// 各出力形式(ConcreteStrategy)
class PdfExportStrategy implements ExportStrategy {
exportData(data: string): void {
console.log(`PDF出力: ${data}`);
}
}
class CsvExportStrategy implements ExportStrategy {
exportData(data: string): void {
console.log(`CSV出力: ${data}`);
}
}
class XmlExportStrategy implements ExportStrategy {
exportData(data: string): void {
console.log(`XML出力: ${data}`);
}
}
// コンテキスト
class Exporter {
constructor(private strategy: ExportStrategy) {}
setStrategy(strategy: ExportStrategy): void {
this.strategy = strategy;
}
export(data: string): void {
console.log("開始ログ");
this.strategy.exportData(data);
console.log("完了ログ");
}
}
// 利用例
const exporter = new Exporter(new PdfExportStrategy());
exporter.export("帳票データ");
exporter.setStrategy(new CsvExportStrategy());
exporter.export("ユーザー一覧");
<?php
interface ExportStrategy {
public function exportData(string $data): void;
}
class PdfExportStrategy implements ExportStrategy {
public function exportData(string $data): void {
echo "PDF出力: {$data}\n";
}
}
class CsvExportStrategy implements ExportStrategy {
public function exportData(string $data): void {
echo "CSV出力: {$data}\n";
}
}
class XmlExportStrategy implements ExportStrategy {
public function exportData(string $data): void {
echo "XML出力: {$data}\n";
}
}
class Exporter {
public function __construct(private ExportStrategy $strategy) {}
public function setStrategy(ExportStrategy $strategy): void {
$this->strategy = $strategy;
}
public function export(string $data): void {
echo "開始ログ\n";
$this->strategy->exportData($data);
echo "完了ログ\n";
}
}
// 利用例
$exporter = new Exporter(new PdfExportStrategy());
$exporter->export("帳票データ");
$exporter->setStrategy(new CsvExportStrategy());
$exporter->export("ユーザー一覧");
from abc import ABC, abstractmethod
class ExportStrategy(ABC):
@abstractmethod
def export_data(self, data: str):
pass
class PdfExportStrategy(ExportStrategy):
def export_data(self, data: str):
print(f"PDF出力: {data}")
class CsvExportStrategy(ExportStrategy):
def export_data(self, data: str):
print(f"CSV出力: {data}")
class XmlExportStrategy(ExportStrategy):
def export_data(self, data: str):
print(f"XML出力: {data}")
class Exporter:
def __init__(self, strategy: ExportStrategy):
self._strategy = strategy
def set_strategy(self, strategy: ExportStrategy):
self._strategy = strategy
def export(self, data: str):
print("開始ログ")
self._strategy.export_data(data)
print("完了ログ")
# 利用例
exporter = Exporter(PdfExportStrategy())
exporter.export("帳票データ")
exporter.set_strategy(CsvExportStrategy())
exporter.export("ユーザー一覧")
✅ Explanation
This code applies the Strategy pattern to separate the data export logic (PDF, CSV, XML) into strategies (ExportStrategy)
that can be switched dynamically. The Strategy pattern encapsulates algorithms as separate classes and allows them to be interchangeable at runtime.
1. Overview of the Strategy Pattern
-
Strategy: Defines a common interface for various behaviors
- Represented by
ExportStrategyin this code
- Represented by
-
ConcreteStrategy: Implements the strategy with specific logic
- Represented by
PdfExportStrategy,CsvExportStrategy, andXmlExportStrategy
- Represented by
-
Context: Uses a
Strategyand can dynamically switch it- Represented by
Exporter
- Represented by
2. Key Classes and Their Roles
-
ExportStrategy- Common interface for data export behavior
- Declares the method
exportData(data: string): void
-
PdfExportStrategy,CsvExportStrategy,XmlExportStrategy- Concrete strategy classes implementing
ExportStrategy - Each outputs data in a different format (PDF, CSV, XML)
- Concrete strategy classes implementing
-
Exporter- The context class
- Receives an
ExportStrategyin the constructor and executes it via theexportmethod - Supports dynamic strategy switching via
setStrategy
3. UML Class Diagram
4. Benefits of the Strategy Pattern
- Flexibility: Easily switch between different behaviors at runtime
- Single Responsibility Principle: Each strategy is isolated in its own class, improving maintainability
- Extensibility: New strategies can be added by simply implementing
ExportStrategy
This design is highly effective in scenarios where processing logic needs to be swapped dynamically,
significantly improving code maintainability and extensibility.