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でデザインパターン[3.TemplateMethod]

Last updated at Posted at 2021-03-22

はじめに

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

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

前回はこちら

メモ

  • TSにはfinalがない
    • 継承させないようにするにはどうしたらいいんだろう?
  • TSにはcharがない
    • JSにはcharしかないからしょうがない。富豪的だなあ。

Code

namespace TemplateMethod {
  abstract class AbstractDisplay {
    abstract open(): void;
    abstract print(): void;
    abstract close(): void;

    // TSってfinal使えないんだ・・・
    display() {
      this.open();
      for (let i = 0; i < 5; i++) {
        this.print();
      }
      this.close();
    }
  }

  class CharDisplay extends AbstractDisplay {
    private c: string;

    // TSにはcharはないらしい。独自定義する必要がある
    constructor(c: string) {
      super();

      this.c = c;
    }

    open(): void {
      console.log("<<");
    }
    print(): void {
      console.log(this.c);
    }
    close(): void {
      console.log(">>");
    }
  }

  class StringDisplay extends AbstractDisplay {
    private str: string;

    constructor(str: string) {
      super();

      this.str = str;
    }

    open(): void {
      this.printLine();
    }
    print(): void {
      console.log(`| ${this.str} |`);
    }
    close(): void {
      this.printLine();
    }

    private printLine() {
      let line = "+";
      for (let i = 0; i < this.str.length; i++) {
        line += "-";
      }
      line += "+";
      console.log(line);
    }
  }

  class Main {
    main() {
      const displays: AbstractDisplay[] = [];
      displays.push(new CharDisplay("c"));
      displays.push(new StringDisplay("hello"));
      displays.push(new StringDisplay("こんにちは"));

      for (const display in displays) {
        displays[display].display();
      }
    }
  }

  new Main().main();
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?