0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Compositeパターン

Posted at

1. Composite パターンとは?

  • 定義: オブジェクトをツリー構造に構成し、個々のオブジェクトと複合オブジェクトを統一的に扱うデザインパターン
  • 目的: 部分-全体の階層構造を単一のインターフェースで操作
  • カテゴリ: 構造パターン(Structural Pattern)

2. どんな時に使う?

  • 階層的な構造(例:ファイルシステム、組織図)を扱う場合
  • 単一オブジェクトと複合オブジェクトを同じ方法で扱いたい場合

3. 構造

  • Component: 葉と複合オブジェクトの共通インターフェース
  • Leaf: 末端オブジェクト
  • Composite: 子コンポーネントを管理する複合オブジェクト

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

ファイルとフォルダの階層構造の例。

// Component
interface FileSystemComponent {
    void display();
}

// Leaf
class File implements FileSystemComponent {
    private String name;
    
    public File(String name) {
        this.name = name;
    }
    
    public void display() {
        System.out.println("File: " + name);
    }
}

// Composite
class Folder implements FileSystemComponent {
    private String name;
    private List<FileSystemComponent> components = new ArrayList<>();
    
    public Folder(String name) {
        this.name = name;
    }
    
    public void add(FileSystemComponent component) {
        components.add(component);
    }
    
    public void display() {
        System.out.println("Folder: " + name);
        for (FileSystemComponent component : components) {
            component.display();
        }
    }
}

// クライアントコード
public class Main {
    public static void main(String[] args) {
        Folder root = new Folder("root");
        File file1 = new File("file1.txt");
        File file2 = new File("file2.txt");
        Folder subFolder = new Folder("subFolder");
        File file3 = new File("file3.txt");
        
        root.add(file1);
        root.add(subFolder);
        subFolder.add(file2);
        subFolder.add(file3);
        
        root.display();
    }
}

5. メリット

  • 階層構造を統一的に扱える
  • 新しいコンポーネントの追加が容易
  • クライアントコードがシンプルになる

6. デメリット

  • 葉と複合オブジェクトの役割が曖昧になる場合がある
  • 複雑な操作では制限が生じる可能性

7. 実際の使用例

  • ファイルシステム(ファイルとフォルダ)
  • GUIコンポーネント(ボタン、パネル、ウィンドウ)
  • 組織図(社員、部署)

8. まとめ

  • Compositeパターンは、階層構造を統一的に扱いたい場合に有効
  • ツリー構造の操作を簡潔にし、拡張性を提供
  • 設計時に葉と複合オブジェクトの役割を明確にすることが重要!
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?