0
0

More than 1 year has passed since last update.

[JavaScript]テンプレートメソッドパターン・シングルトンパターン

Last updated at Posted at 2023-04-28

この記事の内容

JavaScript でのテンプレートメソッドパターン・シングルトンパターンの実装方法のメモ

この記事を書くきっかけ

最近、JavaScript でコーディングする機会が増えたため

デザインパターンに則ってコーディングする理由

拡張性・メンテナンス性を担保する

デザインパターン

テンプレートメソッドパターン

スーパークラスに処理の流れを定義し、サブクラスに処理の詳細を定義するデザインパターンのこと

シングルトンパターン

そのクラスのインスタンスが1つしか生成されないことを保証するデザインパターンのこと

コード

sample.js
class Product {
    constructor(name,price){
        this.name = name;
        this.price = price;
    }
    // サブクラスが処理未実装の場合、エラーを投げる
    getInfo = () => { throw new Error("Line3 Error") };
}

// テンプレートメソッドパターン
class Food extends Product {
    constructor(name,price,calorie){
        super(name,price);
        this.calorie = calorie;
    }
    getInfo = () => { console.log(`${this.name} ¥${this.price} ${this.calorie}cal`);};
}

class Drink extends Product {
    constructor(name,price,amount){
        super(name,price);
        this.amount = amount;
    }
    getInfo = () => { console.log(`${this.name} ¥${this.price} ${this.amount}ml`); };
}

class ProductMaster {
    // シングルトンパターン
    static #productMaster = new ProductMaster();
    static getInstance = () => this.#productMaster;

    #products = [];

    constructor(){
        const food1 = new Food("food1",100,123);
        const drink1 = new Drink("drink1",148,500);
        const product1 = new Product("product1",1000);
        this.#products.push(food1);
        this.#products.push(drink1);
        this.#products.push(product1);
    }

    getProducts = () => this.#products;
}

const master = ProductMaster.getInstance();
const master2 = ProductMaster.getInstance();

// 同じインスタンスかどうか確認
console.log(master === master2);
console.log(master.getProducts() === master2.getProducts());

// 具体的な処理をサブクラスに任せる
master.getProducts().forEach( product => {
    product.getInfo();
});

実行結果

true
true
food1 ¥100 123cal
drink1 ¥148 500cal
/Users/XXXXXX/Desktop/JavaScript/sample.js:6
    getInfo = () => { throw new Error("Line3 Error") };
                      ^

Error: Line3 Error
(中略)
0
0
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
0