September 04, 2018
前回の記事、を読み直して、Decoratorパターンの復習をする。
自分の言葉で
あるクラスに機能を追加する方法として、継承で実現するのではなく、合成(委譲)で機能を実現する方法である。また動的に機能の追加をすることが可能である。
より詳しく
http://zecl.hatenablog.com/entry/20070603/p1
クラス図(wikipediaより)
wikipediaのサンプルコード
| // 出所 https://ja.wikipedia.org/wiki/Decorator_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3 | |
| /** 価格をあらわすインタフェース */ | |
| 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() | |
| ); | |
| } | |
| } | 
中心となるオブジェクトがあって、その役割を果たすのがConcreteComponentである。その中心となるオブジェクトに装飾する役割を果たすクラスがConcreteDecoratorである。
Written by Ta Toshio who lives and works in Saitama, Japan .You should follow him on Twitter