Decorator パターンは、動的にオブジェクトに機能を追加するための設計手法です。この方法は単純な継承よりも柔軟性があり、JavaのSystem.IOやログ機能の実装で広く利用されています。
まず抽象インターフェースを定義します。
public abstract class Component
{
public abstract void Execute();
}
次に基となる具象クラスを実装します。
public class SmartPhoneComponent : Component
{
public override void Execute()
{
Console.WriteLine("スマートフォンの基本操作");
}
}
機能拡張用のデコレータ抽象クラスです。
public abstract class FunctionDecorator : Component
{
protected Component phone;
public FunctionDecorator(Component phone)
{
this.phone = phone;
}
public override void Execute()
{
if(phone != null)
{
phone.Execute();
}
}
}
GPS機能を追加する具象デコレータです。
public class GPSFunctionDecorator : FunctionDecorator
{
public GPSFunctionDecorator(Component phone) : base(phone) {}
public override void Execute()
{
base.Execute();
AddGPSSpecificFunction();
}
private void AddGPSSpecificFunction()
{
Console.WriteLine("GPS機能を起動します");
}
}
ブルートゥース機能を追加する具象デコレータです。
public class BluetoothFunctionDecorator : FunctionDecorator
{
public BluetoothFunctionDecorator(Component phone) : base(phone) {}
public override void Execute()
{
base.Execute();
AddBluetoothSpecificFunction();
}
private void AddBluetoothSpecificFunction()
{
Console.WriteLine("ブルートゥース機能を起動します");
}
}
クライアント側での利用例です。
static void Main(string[] args)
{
Component phone = new SmartPhoneComponent();
phone.Execute(); // 基本操作
phone = new GPSFunctionDecorator(phone);
phone.Execute(); // GPS機能付き
phone = new BluetoothFunctionDecorator(phone);
phone.Execute(); // GPS+ブルートゥース機能付き
Console.Read();
}
Decorator パターンのメリットは以下の通りです:
- 機能拡張を柔軟に行える
- 継承よりも低耦合な実装が可能
- 複数の機能拡張を層状に組み合わせることが出来る
このパターンは以下のような場面で特に役立ちます:
- UIAlert ロギング機能の追加
- データ入出力の加工
- ネットワーク通信のプロトコルラッパー