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

More than 3 years have passed since last update.

TypeScriptでデザインパターン[4.FactoryMethod]

Posted at

はじめに

Typescriptでデザインパターンをやっていくシリーズ(にする予定です)

結城 浩さんの「Java言語で学ぶデザインパターン入門」をTSに置き換えてTS力をあげていこうという趣旨です。

前回はこちら

メモ

  • TSにはfinalがない
    • 継承させないようにするにはどうしたらいいんだろう?(2度目)
  • FactoryMethodパターンの使い所
    • 複雑なインスタンス生成処理をカプセル化
    • インスタンス化前後の処理を強制
    • インスタンスの生成は子に任せる(Wikipediaの例
    • そんなところか? 抽象度が高すぎていまいちわからない。

Code

namespace FactoryMethod {
  abstract class Product {
    abstract use(): void;
  }

  abstract class Factory {
    create(owner: string): Product {
      const p = this.createProduct(owner);
      this.registerProduct(p);
      return p;
    }

    abstract createProduct(owner: string): Product;
    abstract registerProduct(product: Product): void;
  }

  class IDCard extends Product {
    private owner: string;
    constructor(owner: string) {
      super();
      console.log(owner + "のカードを作ります。");
      this.owner = owner;
    }
    use(): void {
      console.log(this.owner + "のカードを使います。");
    }
    getOwner(): string {
      return this.owner;
    }
  }

  class IDCardFactory extends Factory {
    private owners: string[] = [];

    createProduct(owner: string): Product {
      return new IDCard(owner);
    }
    registerProduct(product: Product): void {
      this.owners.push((product as IDCard).getOwner());
    }
    public getOwners(): string[] {
      return this.owners;
    }
  }

  class Main {
    main() {
      const factory = new IDCardFactory();
      const card1 = factory.create("つざき");
      const card2 = factory.create("ふじいかぜ");
      const card3 = factory.create("ほしのげん");
      card1.use();
      card2.use();
      card3.use();
    }
  }
  new Main().main();
}


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