【S4】問8解答例

 このコードは、オフィスドキュメントをエクスポートおよび編集するためのクラスとインターフェースを提供しています。
ExportableEditableという2つのインターフェースがあり、これらを実装することで、オブジェクトがエクスポートと編集の機能を持つことができます。
Spreadsheetクラスは両方のインターフェースを実装し、Spreadsheetオブジェクトはエクスポートと編集の両方の操作が可能です。
一方、ReportクラスはExportableインターフェースを実装し、Reportオブジェクトはエクスポート機能を提供します。
このリファクタリングにより保守性と拡張性が改善されました。

<?php

/**
 * 出力可能
 */
interface Exportable
{
    public function export(): void;
}
                    
<?php

/**
 * 編集可能
 */
interface Editable
{
    public function edit(): void;
}
                    
<?php

/**
 * スプレッドシートクラス
 */
class Spreadsheet implements Exportable, Editable
{
    private string $title;

    public function __construct(string $title)
    {
        $this->title = $title;
    }

    public function export(): void
    {
        echo "Exporting Spreadsheet: $this->title" . PHP_EOL;
    }

    public function edit(): void
    {
        echo "Editing Spreadsheet: $this->title" . PHP_EOL;
    }
}
                    
<?php

/**
 * レポートクラス
 */
class Report implements Exportable
{
    private string $title;

    public function __construct(string $title)
    {
        $this->title = $title;
    }

    public function export(): void
    {
        echo "Exporting Report: {$this->title}" . PHP_EOL;
    }
}
                    
<?php

// 使用例
$spreadsheet = new Spreadsheet("Excel Sheet");
$spreadsheet->export();
$spreadsheet->edit();

$report = new Report("Monthly Report");
$report->export();