1
1

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.

【デザインパターン】JavaScriptで学ぶFacade

Last updated at Posted at 2021-09-04

はじめに

現在デザインパターンについて勉強中です。
今回はFacadeついてまとめました。

Facade

Facadeはサブシステムを利用するユーザーの用途に合わせたインターフェースを提供するための、構造に関するデザインパターンの一つです。
サブシステム間の独立性を高めることを目的としたデザインパターンであり、ユーザはFacadeを経由することで、内部の実装を意識せずにサブシステムを利用することができます。

実装例

入力したテキストを保存write()したり、指定したテキストを取り出すgetCharAt()ような機能をもったConsoleクラス(Facadeクラス)を考えます。
これらの操作を行うにあたってはテキストの表示分の領域を確保してあげる必要などがあります。
新しくViewportクラスとBufferクラスをつくることで、ユーザがそのような内部の実装を意識せずにConsoleクラスを利用することができるようになります。

class Buffer extends Array
{
  constructor(width=30, height=20)
  {
    super();
    this.width = width;
    this.height = height;
    this.alloc(width*height);
  }

  write(text, position=0)
  {
    // write to the buffer
  }
}

class Viewport
{
  constructor(buffer=new Buffer())
  {
    this.buffer = buffer;
    this.offset = 0;
  }

  append(text, pos)
  {
    this.buffer.write(text, pos + this.offset);
  }

  getCharAt(index)
  {
    return this.buffer[this.offset + index];
  }
}

class Console
{
  constructor()
  {
    this.buffer = new Buffer();
    this.currentViewport = new Viewport(
      this.buffer
    );
    this.buffers = [this.buffer];
    this.viewports = [this.currentViewport];
  }

  write(text)
  {
    this.currentViewport.buffer.write(text);
  }

  getCharAt(index)
  {
    return this.currentViewport.getCharAt(index);
  }
}

参考資料

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?