Factory Method
概要
生成したいインスタンスの初期化処理をオーバーライドで切り替えるパターン。
使い方
bad
class Dialog {
render(labels: string[]) {
labels.forEach((label) => {
const button = new Button();
button.onClick(() => this.close());
button.render();
});
}
}
これだとButtonのインスタンスを別のインスタンスに変えたいときに、丸ごと別のメソッドやクラスの実装に変える必要がある
good
abstract class Dialog {
render(labels: string[]) {
labels.forEach(() => {
const button = this.createButton();
button.onClick(() => this.close());
button.render();
});
}
protected abstract createButton(): Button;
}
class PrimaryDialog extends Dialog {
protected createButton() { return new PrimaryButton(); }
}
class SecondaryDialog extends Dialog {
protected createButton() { return new SecondaryButton(); }
}
dialogをに配置するボタンを切り替えるために継承を使うことでButtonの種類を切り替えやすくなった
使い所
類似した複数のクラスに対してインスタンスの生成だけを切り替えたい時に役立つ
ただし、TSの場合は生成する型も縛れるし、その関数を引数で渡せるのでDIでいいことの方が多そう