Decorator パターン
出典: フリー百科事典『ウィキペディア(Wikipedia)』
Decorator パターン(デコレータ・パターン)とは、GoF(Gang of Four; 4人のギャングたち)によって定義されたデザインパターンの1つである。 このパターンは、既存のオブジェクトに新しい機能や振る舞いを動的に追加することを可能にする。
目次 |
[編集] クラス図
Decorator パターンのクラス図を以下に挙げる。
[編集] 概要
Decorator パターンの方針は、既存のオブジェクトを新しい Decorator オブジェクトでラップすることである。 その方法として、Decorator のコンストラクタの引数でラップ対象の Component オブジェクトを読み込み、コンストラクタの内部でそのオブジェクトをメンバに設定することが一般的である。
Decorator パターンは、既存のクラスを拡張する際にクラスの継承の代替手段として用いられる。継承がコンパイル時に機能を拡張するのに対し、Decorator パターンはプログラムの実行時に機能追加をする点が異なる。
[編集] 利用例
Java による利用例を以下に挙げる。
/** 価格をあらわすインタフェースです. */ interface Price{ int getValue(); } /** 原価を表すクラスです. */ class PrimePrice implements Price{ private int value; PrimePrice(int value){ this.value = value; } public int getValue(){ return this.value; } } /** マージンを介する価格です. */ abstract class MarginPrice implements Price{ protected Price originalPrice; MarginPrice(Price price){ this.originalPrice = price; } } /** 設定された利益を仕入れ価格に上乗せする Price です. */ class WholesalePrice extends MarginPrice{ private int advantage; WholesalePrice(Price price, int advantage){ super(price); this.advantage = advantage; } public int getValue(){ return this.originalPrice.getValue() + advantage; } } /** 仕入れ価格の 2 倍の値段を提示する Price です */ class DoublePrice extends MarginPrice{ DoublePrice(Price price){ super(price); } public int getValue(){ return this.originalPrice.getValue() * 2; } } public class DecoratorTest{ public static void main(String[] argv){ System.out.println( new WholesalePrice( new DoublePrice( new WholesalePrice( new DoublePrice( new PrimePrice(120) ) ,80 ) ) ,200 ) .getValue() ); } }
クラス図との関連は以下の通りである。
- Component
Price- ConcreteComponent
PrimePrice- Decorator
MarginPrice- ConcreteDecorator
WholesalePrice,DoublePrice
[編集] 関連項目
|
|||||||||||