今回は Bridge パターン(一覧)。
Bridge パターンの登場人物
- @Abstraction → 型
- implementorType : Class<?>
- @ImplementorInstance → フィールド
- @Implementor → 型
- abstractionType : Class<?>
- @ConcreteImplementor → 具象クラス
- implementorType : Class<?>
- @RefinedAbstraction → 型
- abstractionType : Class<?>
- @RefinedMethod → メソッド
アノテーション定義
上記の定義の具体的な Java コード。
package org.waman.tools.design.gof.structural; import java.lang.annotation.*; public final class BridgePattern { private BridgePattern(){} @Target(ElementType.TYPE) public static @interface Abstraction{ Class<?> implementorType() default Void.class; @Target(ElementType.FIELD) public static @interface ImplementorInstance{} } @Target(ElementType.TYPE) public static @interface Implementor{ Class<?> abstractionType() default Void.class; } @Target(ElementType.TYPE) public static @interface ConcreteImplementor{ Class<?> implementorType() default Void.class; } @Target(ElementType.TYPE) public static @interface RefinedAbstraction{ Class<?> abstractionType() default Void.class; @Inherited @Target(ElementType.METHOD) public static @interface RefinedMethod{} } }
サンプルコード in 『Java 言語で学ぶデザインパターン入門』
Display.java
@Abstraction 役のクラス。
import org.waman.tools.design.gof.structural.BridgePattern; import org.waman.tools.design.gof.structural.BridgePattern.Abstraction.ImplementorInstance; @BridgePattern.Abstraction(implementorType = DisplayImpl.class) public class Display { @ImplementorInstance private DisplayImpl impl; ... public final void display() { open(); print(); close(); } public void open() {/* this.impl を使う処理 */} public void print() {/* this.impl を使う処理 */} public void close() {/* this.impl を使う処理 */} }
DisplayImpl.java
@Implementor 役のクラス。
import org.waman.tools.design.gof.structural.BridgePattern; @BridgePattern.Implementor public abstract class DisplayImpl { public abstract void rawOpen(); public abstract void rawPrint(); public abstract void rawClose(); }
StringDisplayImpl.java
@ConcreteImplementor 役のクラス。
import org.waman.tools.design.gof.structural.BridgePattern; @BridgePattern.ConcreteImplementor(implementorType = DisplayImpl.class) public class StringDisplayImpl extends DisplayImpl { ... @Override public void rawOpen() {...} @Override public void rawPrint() {...} @Override public void rawClose() {...} }
CountDisplay.java
@RefinedAbstraction 役のクラス。
import org.waman.tools.design.gof.structural.BridgePattern; import org.waman.tools.design.gof.structural.BridgePattern.RefinedAbstraction.RefinedMethod; @BridgePattern.RefinedAbstraction(abstractionType = Display.class) public class CountDisplay extends Display { ... @RefinedMethod public void multiDisplay(int times) {...} }