「Decorator」という英単語は、「装飾者」を意味します。
このパターンは、源となるオブジェクトに、機能という飾り付けをどんどん被せていき、要求にあうオブジェクトに仕立て上げていくパターンです。また、飾り枠と中身を同一視することでより柔軟な機能拡張方法を提供します。
Decoratorパターンのクラス図
1. Component.java
public abstract class Component { public abstract void method1(); public abstract void method2(); }
2. ConcreteComponent.java
public class ConcreteComponent extends Component { public void method1() { System.out.print("ConcComp-m1()"); } public void method2() { System.out.println("ConcComp-m2()"); } }
3. Decorator.java
public abstract class Decorator extends Component{ protected Component component; public Decorator(Component component) { this.component = component; } }
4-1. ConcreteDecoratorA.java
public class ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component component) { super(component); } public void method1() { System.out.print("ConcDecoA-m1() {"); component.method1(); System.out.print("}"); } public void method2() { System.out.println("ConcDecoA-m2() {"); component.method2(); System.out.println("}"); } }
4-2. ConcreteDecoratorB.java
public class ConcreteDecoratorB extends Decorator { public ConcreteDecoratorB(Component component) { super(component); } public void method1() { System.out.print("ConcDecoB-m1() {"); component.method1(); System.out.print("}"); } public void method2() { System.out.println("ConcDecoB-m2() {"); component.method2(); System.out.println("}"); } }
5. Client.java
public class Client { public static void main(String[] args) { Component co = new ConcreteComponent(); co.method1(); System.out.print("\n\n"); co.method2(); System.out.print("\n"); Component coA = new ConcreteDecoratorA(co); coA.method1(); System.out.print("\n\n"); coA.method2(); System.out.print("\n"); Component coB = new ConcreteDecoratorB(coA); coB.method1(); System.out.print("\n\n"); coB.method2(); } }
C:\sample\desin_pattern\decorator>javac Client.java [Enter] C:\sample\desin_pattern\decorator>java Client [Enter] ConcComp-m1() ConcComp-m2() ConcDecoA-m1() {ConcComp-m1()} ConcDecoA-m2() { ConcComp-m2() } ConcDecoB-m1() {ConcDecoA-m1() {ConcComp-m1()}} ConcDecoB-m2() { ConcDecoA-m2() { ConcComp-m2() } }