今回は Strategy パターン(一覧)。
Strategy パターンの登場人物
- @Context → 型
- strategyType : Class<?>
- @StrategyInstance → フィールド
- @Strategy → 型
- @ConcreteStrategy → 具象クラス
- strategyType : Class<?>
アノテーション定義
上記の定義の具体的な Java コード。
package org.waman.tools.design.gof.behavioral; import java.lang.annotation.*; public final class StrategyPattern { private StrategyPattern(){} @Target(ElementType.TYPE) public static @interface Context{ Class<?> strategyType() default Void.class; @Inherited @Target(ElementType.FIELD) public static @interface StrategyInstance{} } @Target(ElementType.TYPE) public static @interface Strategy{} @Target(ElementType.TYPE) public static @interface ConcreteStrategy{ Class<?> strategyType() default Void.class; } }
サンプルコード in 『Java 言語で学ぶデザインパターン入門』
Player.java
@Context 役のクラス。
import org.waman.tools.design.gof.behavioral.StrategyPattern; import org.waman.tools.design.gof.behavioral.StrategyPattern.Context.StrategyInstance; import org.waman.tools.design.gof.behavioral.StrategyPattern.Context.UseStrategy; @StrategyPattern.Context(strategyType = Strategy.class) public class Player { @StrategyInstance private Strategy strategy; ... }
Strategy.java
@Strategy 役のインターフェース。
import org.waman.tools.design.gof.behavioral.StrategyPattern; @StrategyPattern.Strategy public interface Strategy { Hand nextHand(); void study(boolean win); }
WinningStrategy.java
@ConcreteStrategy 役の具象クラス群。
import org.waman.tools.design.gof.behavioral.StrategyPattern; @StrategyPattern.ConcreteStrategy(strategyType = Strategy.class) public class WinningStrategy implements Strategy { ... @Override public Hand nextHand() {...} @Override public void study(boolean win) {...} }
import org.waman.tools.design.gof.behavioral.StrategyPattern; @StrategyPattern.ConcreteStrategy(strategyType = Strategy.class) public class ProbStrategy implements Strategy { ... @Override public Hand nextHand() {...} @Override public void study(boolean win) {...} }