1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ファクトリーパターンとは

Last updated at Posted at 2022-04-02

ファクトリーパターンとは

OOPのデザインパターンの代表的なものの一つで、

  • クライアントが欲しいインスタンスを直接newするのではなくファクトリークラスが代わりにインスタンスを作成する
  • 作成されるクラスはインターフェースを埋め込んでおり、インスタンス後の操作も具体的な実装を読まなくてもできる

というものです。インターフェースによる抽象化をインスタンス生成時にまで敷衍したイメージです。同じインターフェースを埋め込んだり同じ抽象クラスを継承しているクラスが多いときに特に威力を発揮します。

原始的なファクトリークラス

これもファクトリークラスといえばファクトリークラス。作成対象のクラスが増えるたびにファクトリークラスの方も修正しなくてはいけない。

public class ProductFactory{
	public Product createProduct(String ProductID){
		if (ProductID==ID1)
			return new OneProduct();
		if (ProductID==ID2)
			return new AnotherProduct();
		... // so on for the other Ids
		
        return null; //if the id doesn't have any of the expected values
    }
    ...
}

IDからインスタンスを自動生成するファクトリークラス

たぶん一般的に使われている方法がこれ。コード量は増えるけど、

  • クライアントはファクトリーに欲しいクラスのIDだけ渡せばいい
  • ファクトリーは作成対象クラスにどんな種類があるか知らなくていい

等、三者がうまく疎結合になっている。

// 作成対象クラスの抽象クラス.
abstract class Product
{
	public abstract Product createProduct();
	...
}

// 作成対象クラス.
class OneProduct extends Product
{
	...
    // クラスがロードされた時にIDを登録しておく.
	static
	{
		ProductFactory.instance().registerProduct("ID1", new OneProduct());
	}

    // 自身をインスタンス化する.
	public OneProduct createProduct()
	{
		return new OneProduct();
	}
	...
}

class ProductFactory
{
    // 作成対象クラスのIDを登録する.
	public void registerProduct(String productID, Product p)    {
		m_RegisteredProducts.put(productID, p);
	}

    // クライアントから渡されたIDを元に作成対象クラスのインスタンスを作成する.
	public Product createProduct(String productID){
		((Product)m_RegisteredProducts.get(productID)).createProduct();
	}
}
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?