倭マン's BLOG

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

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

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

Flyweight パターンの登場人物

  • @FlyweightFactory → 型
    • flyweightType : Class<?>
    • @Pool → フィールド
    • @GetFlyweight → メソッド
  • @Flyweight → 型
  • @ConcreteFlyweight → 具象クラス
    • flyweightType : Class<?>
  • @UnsharedConcreteFlyweight → 具象クラス
    • flyweightType : Class<?>
  • @Client → 型
    • flyweightType : Class<?>

アノテーション定義


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

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

import java.lang.annotation.*;

public final class FlyweightPattern {
    
    private FlyweightPattern(){}

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

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

        @Inherited @Target(ElementType.FIELD)
        public static @interface Pool{}

        @Inherited @Target(ElementType.METHOD)
        public static @interface GetFlyweight{}
    }

    @Target(ElementType.TYPE)
    public static @interface Flyweight{}

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

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

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

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


BigCharFactory.java

@FlyweightFactory 役のクラス。

import org.waman.tools.design.gof.structural.FlyweightPattern;
import org.waman.tools.design.gof.structural.FlyweightPattern.FlyweightFactory.GetFlyweight;
import org.waman.tools.design.gof.structural.FlyweightPattern.FlyweightFactory.Pool;

@FlyweightPattern.FlyweightFactory(flyweightType = BigChar.class)
public class BigCharFactory {
    
    @Pool private HashMap<String, BigChar> pool = new HashMap<String, BigChar>();
    
    private static BigCharFactory INSTANCE = new BigCharFactory();
    
    private BigCharFactory() {}

    public static BigCharFactory getInstance() {
        return INSTANCE;
    }
    
    @GetFlyweight public synchronized BigChar getBigChar(char charname) {...}
}

BigChar.java

@Flyweight, @ConcreteFlyweight 役のクラス。 @UnsharedConcreteFlyweight 役のクラスは出てきません。

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

@FlyweightPattern.Flyweight
@FlyweightPattern.ConcreteFlyweight(flyweightType = BigChar.class)
public class BigChar {
    ...
}

BigString.java

@Client 役のクラス。

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

@FlyweightPattern.Client(flyweightType = BigChar.class)
public class BigString {
    ...
}

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