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

Posted at

はじめに

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

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

前回はこちら

メモ

  • コピーしてインスタンスを作る
  • 連想配列の型定義{ [key: string]: Product }
  • ts(js)にはObject.clone()はないし自前で実装すると難しいので、ライブラリを使うのがいいらしい。cloneというパッケージを使った。

Code

npm install clone
npm install @types/clone
import clone from "clone";

namespace Prototype {
  interface Clonable {
    createClone: () => Clonable;
  }
  interface Product extends Clonable {
    use: (s: string) => void;
    createClone: () => Product;
  }

  class Manager {
    showcase: { [key: string]: Product } = {};
    register(name: string, proto: Product) {
      this.showcase[name] = proto;
    }

    create(protoName: string): Product {
      const p: Product = this.showcase[protoName];
      return p.createClone();
    }
  }

  class MessageBox implements Product {
    symbol: string;
    constructor(symbol: string) {
      this.symbol = symbol;
    }
    use(s: string): void {
      console.log(`this is messagebox. ${this.symbol}. ${s}`);
    }
    createClone(): Product {
      return clone<Product>(this);
    }
  }

  class UnderlinePen implements Product {
    symbol: string;
    constructor(symbol: string) {
      this.symbol = symbol;
    }
    use(s: string): void {
      console.log(`this is underlinepen. ${this.symbol}. ${s}`);
    }
    createClone(): Product {
      return clone<Product>(this);
    }
  }

  class Main {
    main() {
      const manager = new Manager();

      const pen = new UnderlinePen("-");
      const box1 = new MessageBox("+");
      const box2 = new MessageBox("*");

      manager.register("pen1", pen);
      manager.register("box1", box1);
      manager.register("box2", box2);

      const p1 = manager.create("pen1");
      p1.use("hello");
      const b1 = manager.create("box1");
      b1.use("hello");
      const b2 = manager.create("box2");
      b2.use("hello");
    }
  }

  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?