はじめに
現在デザインパターンについて勉強中です。
今回は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);
}
}
参考資料