LoginSignup
3
2

More than 3 years have passed since last update.

JavaScriptでFactory Pattern

Last updated at Posted at 2019-07-16

Factory pattern

生成する時、最中などに生成するクラスを決定するデザインパターン。

本記事の目的

サーバサイドのNode.jsでDDDで開発したくて、使える自分用のテンプレートとして記述。

使いどころ

処理から呼び出している複数のメソッドの中に同じような分岐(if, switch)がでてきて、もう同じものを見たくない時に使えるやつです。

免責事項

純粋なFactoryパターンの場合では以下のmainclass.jsは不要だと思います。
こちらはサーバサイドのNode.jsで動かしています。
フロントエンドでは動作確認しておりません。

お願いごと

間違っている個所などあれば、ご指摘いただければ幸いです。

Directory

※すべて同じディレクトリ

index.js //試す時はこれを実行する
factoryClass.js
mainclass.js
subclass_a.js
subclass_b.js

Source

index.js
const factory = require('./factoryClass');

// constの部分を差し替えてみると生成されるクラスが違うのがわかる
// const type = "main" 
// const type = "subA"
const type = "subBB"
let name = factory.init(type);
console.log(name.getString());
factoryClass.js
const main = require('./mainclass');
const subA = require('./subclass_a');
const subBB = require('./subclass_b');

class factory {

    init(type){
        if(type === "main"){
            return new main(type)
        }

        if(type === "subA"){
            return new subA(type)
        }

        if(type === "subBB"){
            return new subBB(type)
        }
    }
}

module.exports = new factory();
mainclass.js
class mainclass {
    constructor(obj){
        this.obj = obj;
    }

    getString(){
        return "from main obj" + this.obj;
    }
}

module.exports = mainclass;
subclass_a.js
const main = require('./mainclass');

class subClassA extends main {
    constructor(obj){
        super(obj)
    }

    getString(){
        return "from subClassA" + this.obj;
    }
}

module.exports = subClassA;
subclass_b.js
const main = require('./mainclass');

class subClassBB extends main {
    constructor(obj){
        super(obj)
    }

    // getString(){
    //     return "from subClassBB" + this.obj;
    // }
}

module.exports = subClassBB;

動かし方

node index.js

参考にさせていただいた記事

デザインパターン「Factory Method」

3
2
0

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
3
2