1
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でデザインパターン[2.Adapter]

Posted at

はじめに

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

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

前回はこちら
TypeScriptでデザインパターン[1.Iterator]

メモ

  • namespaceでくくれば同名でも衝突しない
  • Adapterパターンには継承を使ったものと、委譲を使ったものがある
  • 別名Wrapper

Code

// 継承でAdapterを実現するパターン
namespace Adapter_Inheritance {
  interface Print {
    printWeek(): void;
    printStrong(): void;
  }

  class Banner {
    private str: string;

    constructor(str: string) {
      this.str = str;
    }

    public showWithParen(): void {
      console.log("(" + this.str + ")");
    }

    public showWithAster(): void {
      console.log("*" + this.str + "*");
    }
  }

  // 継承でAdapterを実現するパターン
  class PrintBanner extends Banner implements Print {
    constructor(str: string) {
      super(str);
    }

    printWeek(): void {
      this.showWithParen();
    }
    printStrong(): void {
      this.showWithAster();
    }
  }

  const print:Print = new PrintBanner("aaa");
  print.printStrong();
  print.printWeek();
}

// 委譲を使ったもの
namespace Adapter_Delegation {
  abstract class Print {
    abstract printWeek(): void;
    abstract printStrong(): void;
  }

  class Banner {
    private str: string;

    constructor(str: string) {
      this.str = str;
    }

    public showWithParen(): void {
      console.log("(" + this.str + ")");
    }

    public showWithAster(): void {
      console.log("*" + this.str + "*");
    }
  }

  class PrintBanner extends Print {
    private banner: Banner;

    constructor(str: string) {
      super();
      this.banner = new Banner(str);
    }

    printWeek(): void {
      this.banner.showWithParen();
    }
    printStrong(): void {
      this.banner.showWithAster();
    }
  }

  const print:Print = new PrintBanner("bbb");
  print.printStrong();
  print.printWeek();
}

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