倭マン's BLOG

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

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

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

Prototype パターンの登場人物

  • @Prototype → 型
    • @CreateClone → メソッド
  • @ConcretePrototype → 具象クラス
    • prototypeType : Class<?>
  • @Client → 型
    • prototypeType : Class<?>

アノテーション定義


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

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

import java.lang.annotation.*;

public final class PrototypePattern {
    
    private PrototypePattern(){}
        
    @Target(ElementType.TYPE)
    public static @interface Prototype{
        @Inherited @Target(ElementType.METHOD)
        public static @interface CreateClone{}
    }
        
    @Target(ElementType.TYPE)
    public static @interface ConcretePrototype{
        Class<?> prototypeType() default Void.class;
    }
        
    @Target(ElementType.TYPE)
    public static @interface Client{
        Class<?> prototypeType() default Void.class;
    }
}

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


Product.java

@Prototype 役のクラス。

import org.waman.tools.design.gof.creational.PrototypePattern;
import org.waman.tools.design.gof.creational.PrototypePattern.Prototype.CreateClone;

@PrototypePattern.Prototype
public interface Product extends Cloneable {
    void use(String s);
    @CreateClone Product createClone();
}

MessageBox.java, UnderlinePen.java

@ConcretePrototype 役のクラス群。

@PrototypePattern.ConcretePrototype(prototypeType = Product.class)
public class MessageBox implements Product {
    ...
    @Override public void use(String s) {...}
    @Override public Product createClone() {...}
}

@PrototypePattern.ConcretePrototype(prototypeType = Product.class)
public class UnderlinePen implements Product {
    ...
    @Override public void use(String s) {...}
    @Override public Product createClone() {...}
}

Manager.java

@Client 役のクラス。

import org.waman.tools.design.gof.creational.PrototypePattern;

@PrototypePattern.Client(prototypeType = Product.class)
public class Manager {
    ...
}

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