倭マン's BLOG

くだらない日々の日記書いてます。 たまにプログラミング関連の記事書いてます。 書いてます。

「GoF デザインパターン」アノテーション (8) : Composite パターン

今回は Composite パターン一覧)。

Composite パターンの登場人物

  • @Component → 型
    • @Add → メソッド
    • @Remove → メソッド
    • @GetChild → メソッド
  • @Leaf → 型
    • componentType : Class<?>
  • @Composite → 型
    • componentType : Class<?>
    • @Children → フィールド
  • @Client → 型
    • componentType : Class<?>

アノテーション定義


上記の定義の具体的な Java コード。

package org.waman.tools.design.gof.structural;

import java.lang.annotation.*;

public final class CompositePattern {
    
    private CompositePattern(){}

    @Target(ElementType.TYPE)
    public static @interface Component{

        @Inherited @Target(ElementType.METHOD)
        @interface Add{}

        @Inherited @Target(ElementType.METHOD)
        @interface Remove{}

        @Inherited @Target(ElementType.METHOD)
        @interface getChild{}
    }

    @Target(ElementType.TYPE)
    public static @interface Leaf{
        Class<?> componentType() default Void.class;
    }

    @Target(ElementType.TYPE)
    public static @interface Composite{

        Class<?> componentType() default Void.class;

        @Inherited @Target(ElementType.FIELD)
        @interface Children{}
    }

    @Target(ElementType.TYPE)
    public static @interface Client{
        Class<?> componentType() default Void.class;
    }
}

サンプルコード in 『Java 言語で学ぶデザインパターン入門』


Entry.java

@Component 役のクラス。

import org.waman.tools.design.gof.structural.CompositePattern;
import org.waman.tools.design.gof.structural.CompositePattern.Component.Add;

@CompositePattern.Component
public abstract class Entry {
    ...
    public abstract String getName();
    public abstract int getSize();

    @Add public Entry add(Entry entry) throws FileTreatmentException {
        throw new FileTreatmentException();
    }
}

FileTreatmentException は単なる実行時例外。

public class FileTreatmentException extends RuntimeException {
    
    private static final long serialVersionUID = ...;

    public FileTreatmentException() {}
}

Directory.java

@Composite 役のクラス。

import java.util.*;
import org.waman.tools.design.gof.structural.CompositePattern.Composite.Children;

public class Directory extends Entry {
    ...
    @Children private List<Entry> directory = new ArrayList<Entry>();
    
    @Override public String getName() {...}
    @Override public int getSize() {...}
    
    @Override public Entry add(Entry entry) {...}
    ...
}

@Remove, @GetChild 役のメソッドは定義していません。

Main.java

@Client 役のクラス。

import org.waman.tools.design.gof.structural.CompositePattern;

@CompositePattern.Client(componentType = Entry.class)
public class Main {
    public static void main(String... args){...}
}

増補改訂版Java言語で学ぶデザインパターン入門 オブジェクト指向における再利用のためのデザインパターン