既存のクラスの機能を拡張したいが、
既存のクラスは変更したくない場合に間にDecoratorクラスを用いる。
BaseClass.java (既存のクラス)
package gof; public class BaseClass { private int width; private int height; // コンストラクタ public BaseClass(int w, int h){ width = w; height = h; } // 幅を返す public int getWidth(){ return width; } // 高さを返す public int getHeight(){ return height; } }
DecoratorLab.java(Decoratorクラス)
package gof; public class DecoratorLab { BaseClass baseclass; // コンストラクタ public DecoratorLab(int w, int h){ baseclass = new BaseClass(w,h); } // 面積を返す public int getArea(){ return baseclass.getWidth() * baseclass.getHeight(); } }
Decoratorクラスによって面積を返すgetAreaメソッドが拡張されている。
ただ、継承を利用しても同じことができる。