0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

typescriptでデザインパターン(Abstract Factory)

Last updated at Posted at 2022-09-19

やりたいこと

デザインパターンのAbstract Factoryパターンを理解するため、TECSCORE*(1)にJavaで記載されたコードを参考にtypescriptでAbstract Factoryを実装する。

AbstractFactoryのクラス図

キムチ鍋と水炊き鍋を作るためのファクトリーをabstractFactoryで抽象化します。
image.png

実装したコード

// abstract Factory
abstract class AbstractFactory {
    abstract getSoup(): Soup;
    abstract getProtein(): Protein;
}


// ConCreate Factory
// 水炊き鍋
class MizutakiFactory extends AbstractFactory {
    getSoup(): Soup {
        return new MisoSoup();
    }
    getProtein(): Soup {
        return new Chikin()
    }
}
// キムチ鍋
class KimuchiFactory extends AbstractFactory {
    getSoup(): Soup {
        return new KimutiSoup();
    }
    getProtein(): Soup {
        return new Chikin()
    }
}


// abstract Product
// スープ
abstract class Soup { }
// メインディッシュ(タンパク質)
abstract class Protein { }


// concreate Product
// ミソスープ
class MisoSoup extends Soup {
}
// キムチスープ
class KimutiSoup extends Soup {
}
// 鶏肉
class Chikin extends Protein {
}


// 鍋(容器)
class Pot {
    constructor() {
        return 'pot'
    }
}


// なべ
class HotPot {
    pot: Pot;
    soup: Soup;
    protein: Protein;

    constructor(pot: Pot) {
        this.pot = pot;
    };

    public addSoup(soup: Soup) {
        this.soup = soup;
    };

    public addProtein(protein: Protein) {
        this.protein = protein;
    };

}


// 鍋を作ります
class Sample {
    static makeHotPot(type: 1 | 2) {
        const factory: AbstractFactory = this.createFactory(type);
        const hotPot = new HotPot(new Pot());
        hotPot.addSoup(factory.getSoup());
        hotPot.addProtein(factory.getProtein());
        return hotPot;
    }


    static createFactory(type: 1 | 2): AbstractFactory { //1: 水炊き鍋、2: キムチ鍋
        if (type == 1) {
            return new MizutakiFactory()
        }
        else {
            return new KimuchiFactory()
        }
    }
}


// 実行
function main() {
    // 水炊き鍋を作る
    const mizudakiHotpot = Sample.makeHotPot(1);
    console.log(mizudakiHotpot);

    // キムチ鍋を作る
    const kimuchiHotpot = Sample.makeHotPot(2);
    console.log(kimuchiHotpot);
}

main();


    

実行結果

image.png

参考文献

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?